3

greetings all i want to validate an email with javaScript and i need to use the best pattern for the matching please suggest me a good pattern

3
  • You don't want to validate e-mail using JavaScript, since JavaScript can be disabled.
    – Anders
    Commented Dec 13, 2010 at 12:12
  • He may want to double validate. It's perfectly OK to not allow an action early on the client level as long as a server validation also takes place.
    – Alin P.
    Commented Dec 13, 2010 at 12:14
  • The best way to validate an email address is to send an email and check the return value. Please, have a look at these sites: TLD list; valid/invalid addresses; regex for RFC822 email address
    – Toto
    Commented Jul 23, 2020 at 12:33

4 Answers 4

5

In order for you to avoid reinventing the wheel I recommend this quality article on regular-expressions.info.

3

This ^([0-9a-zA-Z]([-\.\+\_\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$ should match most cases. I might get massively down-voted for not including every single edge case (email addresses can have all kinds of crazy combinations) but I don't think I'm exaggerating in saying this will match 99.99% of email addresses.

2

This is the standard validation regular expression: http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html for RFC 822 ;)

You probably want something more simple (taken from http://www.regular-expressions.info/email.html): /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i for JavaScript

2

What you might want to be wary of, if I remember correctly, is the fact that some email servers don't conform to RFC822, so being very strict on the validation might exclude some 'valid' email addresses. Depending on the level of validation that you need, it may be possible to just check that the email address has the correct basic format - something like one or more words separated by periods, followed by an @ symbol, followed by two or more words separated by periods.

Having said this, you may also want to consider why you are validating the email address in the first place.

If you simply want to make sure that the user didn't type it incorrectly, then ask for the email address and a confirmation of the email address, then compare the two to decide whether the address is valid or not. (This is the strategy used by quite a lot of websites)

If you want to know whether the email address is real or not, as part of a registration process, then the registration could be made into a two step process, with a confirmation email being sent to the address that the user supplies in the frist step, and that email contains a link to the second step of the process.

I may be making wild assumptions about your needs, but I may just trigger the appropriate thought processes.

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