DEV Community

loading...

Discussion on: JS: Check if an email is valid

Collapse
andrewbridge profile image
Andrew Bridge

It's probably worth sharing this StackOverflow link: How to validate an email in Javascript

The specific answer linked suggests:

(?:[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])+)\])
Enter fullscreen mode Exit fullscreen mode

...as the most complete answer, meeting the full RFC spec, though it caveats that with reasons why not to use it.

You'd be far better off not validating an email with JS at all and instead using <input type="email" /> to provide immediate user feedback and, of course, strong validation on the server receiving the input. You can still style your inputs based on valid and invalid input and the validation is done for you!

Collapse
mellen profile image
Matt Ellen

It doesn't completely comply to the RFC, as the RFC allows for comments and the regex does not. As one would expect with a regex.

Collapse
andrewbridge profile image
Andrew Bridge

Haha, so even with 321 characters of regex it's not entirely complete.

To be clear, I'm only making the assumption that <input type="email" /> will validate perfectly to the RFC. But I'd rather leave it to a natively supplied tag than write my own either way.

Thread Thread
mellen profile image
Matt Ellen • Edited

I agree. The tag is tested by millions of people, everyday, so if there were errors they would pop up.

On the other hand, I don't see the utility of comments in email addresses.



matt (this is a comment 
(with a nested comment) 
which is patently useless)  .ellen@example.com
Enter fullscreen mode Exit fullscreen mode
Thread Thread
andrewbridge profile image
Andrew Bridge

Someone, somewhere makes heavy use of comments in email addresses I bet. That one person would be positively peeved if we broke their workflow 😆