简体   繁体   中英

Email validation Javascript RegExp

With this RegExp I can easily check if an email is valid or not:

RegExp(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/);

However, this just return true for such addresses:

example@example.com

I also want to accept:

*@example.com

What changes I need to apply on my RegExp?

Thanks in advance

To answer your question literally, you can "augment" your regex:

RegExp(/^([\w.*-]+@([\w-]+\.)+[\w-]{2,4})?$/);

But this is a terrible regex for e-mail validation. Regex is the wrong tool for this. Why do you insist on doing it this way ?

Checking email addresses is not that straightforward, cf. RFC 822, sec 6.1 .

A good list of regexes can be found at http://www.regular-expressions.info/email.html , describing tradeoffs between RFC conformance and practicality.

A couple of things: to accept *@foo.bar :

var expression = /^([\w-\.*]+@([\w-]+\.)+[\w-]{2,4})?$/;//no need to pass it to the RegExp constructor

But this expression does accept -@-.-- , but then again, regex and email aren't all too good a friends. But based on your expression, here's a slightly less unreliable version:

var expression = /^[\w-\.\d*]+@[\w\d]+(\.\w{2,4})$/;

There is an expression that validates all valid types of email addresses, somewhere on the net, though. Look into that, to see why regex validating is almost always going to either exclude valid input or be too forgiving

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM