mozilla / micro-email-validator

DEPRECATED, DO NOT USE THIS PROJECT. Transliteration of html5 email validator in Firefox
Mozilla Public License 2.0
3 stars 4 forks source link

Refactor the email validator #6

Closed TDA closed 9 years ago

TDA commented 9 years ago

The email validator seems too liberal at times, and the code can definitely be made more concise using regexes. Eg: We could replace Lines 11-25 with regexes.

Also, the checks seem unnecessarily verbose, Eg: L23 can be simplified to : if (atPos <1 || atPos === value.length)

Maybe a single regex like this?

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

or if we do not strip trailing or leading spaces:

\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}\b

or for better readability, with grouping to extract username, domain etc: (I am not sure if the third part is legal, so let me know)

\b([\w.%+-]+)@([\w.-]+)\.(\w{2,4})\b

Looking closer at all the checks, I believe this regex would capture all the tests into one(including checking for dot after dot and dash after dot):

\b([\w.%+-]+)@([\w-]+)(?:\.(\w{2,4})){1,3}\b

tested this with:

foo@demo.net
bar.ba@test.co.uk
bar at@test..com
at@test.-abc.com

And only the first two are valid, which is what the validator would have displayed as well. With this one, we can extract the username like so, matches[0] domain-name like so: matches[1] domain-extension like so: matches[2]

I can make a PR if you guys think this is worth the change :) EDIT: If anyone wants to play with the regexes: http://www.regexr.com/ is a good place. @6a68 @pdehaan

jaredhirsch commented 9 years ago

Closing. See discussion in #7.