views:

47

answers:

2

I have this function which will validate an email address. jsLint gives an error with the regular expression complaining about some of the characters being un-escaped.

Is there a way to correctly escape them?

var validateEmail = function(elementValue){
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    return emailPattern.test(elementValue);
};
+6  A: 

The regular expression you are using is valid. But I guess JSLint complains about the missing escape sign in front of - in the character classes:

/^[a-zA-Z0-9._\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,4}$/

Escaping the - inside a character class is only required if it is not at the begin or end of the character class or if it is not denoting a range when used between two characters.

Here are some examples that are valid:

/[-xyz]/    // "-", "x", "y", "z"
/[xyz-]/    // the same as above
/[-]/       // "-"
/[a-z-]/    // "a"-"z", "-"
/[a-b-c]/   // "a"-"b", "-", "c"
Gumbo
+1  A: 

I'm not seeing immediately what needs to be escaped. You might want to try /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i for your Regex. I just neatened it a little and added + and % to the first field.

stocherilac