Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Here I have 2 email validation regexps, which one is better and why?

new RegExp("^[a-zA-Z0-9_-]+@[a-zA-Z0-9-]{2,}[.][a-zA-Z]{2,}$", "i");

new RegExp("^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4})*$", "");
share|improve this question

2 Answers 2

up vote 2 down vote accepted

There probably is no 'good' regexp to validate an email id. The Internet Standard RFC has classified a 500-character long RegExp which according to them is the standard way to validate an email-id. Well, it does work, but it is so messy and almost impossible for most of us to understand.

(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])

If you have understood it, then, you need not read further. But if you haven't, go on.

This page gives a decent info on how to validate an email id using regexp.

I use this one

RegExp("^[A-Z0-9._%+-]+@([A-Z0-9.-]+\.){1,4}[A-Z]{2,4}$","i")

This works fine, atleast for me, but it fails to validate emails on .museum domain or any other domain longer than 4-characters.

Coming to your patterns, both of them are almost same except the fact that the first one uses i modifier and it allows 2 or more than 2 characters as TLD. Hope it helps.

share|improve this answer
    
The other problem with the RFCs is that they only care about syntactically valid email addresses. foobar@yahoo.con may be syntactically valid, but it's probably not what the user intended to type, even if the .con domain exists. –  Brian Dec 26 '12 at 18:22
    
Your suggestion breaks on '@example.com and *@example.com both of which are entirely valid. –  J99 Jul 23 '13 at 12:39
    
IP addresses are valid server destinations, too. –  Dave Jarvis Jul 23 '13 at 17:39

Both are totally broken as they both fail to accept the + character in the local part and one of them requires more than one digit for the domain name. Single-digit domain names are perfectly fine in some TLDs (such as .de).

If you really need more validation than a simple "has the *@*.* format" check, you need to read this answer on Stack Overflow: Using a regular expression to validate an email address

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.