Friday, June 10, 2016

regex - JavaScript Regular Expression Email Validation





This code is always alerting out "null", which means that the string does not match the expression.



var pattern = "^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$"; 


function isEmailAddress(str) {

str = "azamsharp@gmail.com";

alert(str.match(pattern));
return str.match(pattern);

}

Answer




If you define your regular expression as a string then all backslashes need to be escaped, so instead of '\w' you should have '\\w'.



Alternatively, define it as a regular expression:



var pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/; 





BTW, please don't validate email addresses on the client-side. Your regular expression is way too simple to pass for a solid implementation anyway.




See the real thing here: http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...