开发者

Suggest a good pattern for validating email with javaScript? [duplicate]

开发者 https://www.devze.com 2023-01-30 20:41 出处:网络
This question already has answers here: How can I validate an email address in JavaScript? (79 answers)
This question already has answers here: How can I validate an email address in JavaScript? (79 answers) Closed 2 years ago.

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开发者_如何学Go pattern


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


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消