JSHelp JSHelp - 4 months ago 30
Javascript Question

Jquery Value match Regex

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 example@example.com.
I already tried .test() and .match(), what did I do wrong?

Answer
  • Pass a string to RegExp or create a regex using the // syntax
  • Use call regex.test(string), not string.test(regex)

So

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

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