0

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.

2
  • 2
    Looks like you're only matching one character. It should probably be [...]+ Commented Sep 10, 2012 at 17:04
  • 2
    $(this).val() is likely easier to read than $(this).attr('value') Commented Sep 10, 2012 at 17:07

3 Answers 3

2

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._%+-]+$/; 
Sign up to request clarification or add additional context in comments.

Comments

1

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; 

Comments

0

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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.