Jeff Fabiny
Jeff Fabiny

Reputation: 325

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.

Upvotes: 0

Views: 107

Answers (3)

pb2q
pb2q

Reputation: 59627

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;

Upvotes: 1

jbabey
jbabey

Reputation: 46657

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;

Upvotes: 0

Michal Klouda
Michal Klouda

Reputation: 14521

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._%+-]+$/;

Upvotes: 2

Related Questions