Jquery Value match Regex

JavascriptJqueryRegexMatch

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

  • 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');
        }
    });
});

Solution 2 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDeproblemifyView Question on Stackoverflow
Solution 1 - JavascriptArun P JohnyView Answer on Stackoverflow
Solution 2 - JavascriptSean BrightView Answer on Stackoverflow