简体   繁体   中英

regular expression just beginning of email

I want to validate just the beginning of an email address. I will force the user to use my '@company.com' domain, so it is not important to use that. This is the regular expression I'm using:

var validateEmail = /^[A-Z0-9._%+-]$/

And I'm testing it with an alert.

alert(validateEmail.test([$(this).attr('value')]));

The value pulled via jQuery is the user input. Everything I test alerts as false . Does anyone see why? From what I understand, this should mean: beginning of line, character set for alpha-numeric plus the . _ % + - . _ % + - symbols, then end of line. What am I doing wrong? Even just an 'a' alerts as false .

Your regex only matches single character. You need to add + sign or {min, max} to specify minimum and maximum length.

var validateEmail = /^[A-Z0-9._%+-]+$/;

Your regex will only match a single character from your set, add a + to match at least one character from your set:

var validateEmail = /^[A-Z0-9._%+-]+$/;

And you've neglected to include lower-case characters to your regex object:

var validateEmail = /^[A-Za-z0-9._%+-]+$/;

Or set the ignore-case flag:

var validateEmail = /^[A-Z0-9._%+-]+$/i;

You have multiple issues.

  • a fails because it is lower case and your regular expression is case sensitive. You can use the i option to ignore casing.
  • most other valid email adresses would fail because your regular expression only allows 1 character. you can use the + after the character class [...] to allow one or more characters, or * to allow 0 or more.

var validateEmail = /^[A-Z0-9._%+-]+$/i;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM