80

I am trying to validate the input for E-Mail via JQuery:

My JQuery

<script>
/* <![CDATA[ */
  jQuery(function(){
   $( ".mail" ).keyup(function() {
   var VAL = $(this).val();
   var email = new RegExp(^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$);

   if(VAL.test(email)){
   alert('Great, you entered an E-Mail-address');
   }
   });
  });
  /* ]]> */
  </script>

This won't alert even though I entered [email protected]. I already tried .test() and .match(), what did I do wrong?

0

2 Answers 2

109
  • Pass a string to RegExp or create a regex using the // syntax
  • Call regex.test(string), not string.test(regex)

So

jQuery(function () {
    $(".mail").keyup(function () {
        var VAL = this.value;

        var email = new RegExp('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$');

        if (email.test(VAL)) {
            alert('Great, you entered an E-Mail-address');
        }
    });
});
Sign up to request clarification or add additional context in comments.

8 Comments

You can use this.value instead of $(this).val().
Take into account this will not accept lowecase letters.
It's a case sensitive expression so [email protected] isn't accepted while [email protected] is approved. You can modify it to '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$' to solve the problem but there is another issue, in this Regex abc@abcd without any dot is accepted! I suggest this one instead: /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/g but none of these expressions accept an email address when there is a hyphen in domain name like: [email protected], visit this page for the best Regex: link
When constructing a RE with new RegExp, if you pass a sting, you'll need to double-escape backslashes. Eg you have \. in your code, but that's just an unnecessary escape character - '\.' === '.'. Best to avoid new RegExp unless you need to dynamically construct a RE from a variable.
@leo848 $(this).val() just wraps this.value - it's one extra function call to get to the same piece of data, making it unnecessary.
|
14

Change it to this:

var email = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;

This is a regular expression literal that is passed the i flag which means to be case insensitive.

Keep in mind that email address validation is hard (there is a 4 or 5 page regular expression at the end of Mastering Regular Expressions demonstrating this) and your expression certainly will not capture all valid e-mail addresses.

3 Comments

var email = new RegExp('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$', 'i');
I prefer to change it like this
I don't see anything different other than that you are using a string instead of the (arguably preferred) regular expression literal syntax?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.