简体   繁体   中英

Regex Comma Separated Emails

I am trying to get this Regex statement to work

^([_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[az]{2,3})+(\s?[,]\s?|$))+$

for a string of comma separated emails in a textbox using jQuery('#textbox').val(); which passes the values into the Regex statement to find errors for a string like:

"test@test.com, test1@test.com,test2@test.com"

But for some reason it is returning an error. I tried running it through http://regexpal.com/ but i'm unsure ?

NB: This is just a basic client-side test. I validate emails via the MailClass on the server-side using .NET4.0 - so don't jump down my throat re-this. The aim here is to eliminate simple errors.

Escaped Version:

^([_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[az]{2,3})+(\\s?[,]\\s?|$))+$

You can greatly simplify things by first splitting on commas, as Pablo said, then repeatedly applying the regex to validate each individual email. You can also then point out the one that's bad -- but there's a big caveat to that.

Take a look at the regex in the article Comparing E-mail Address Validating Regular Expressions . There's another even better regex that I couldn't find just now, but the point is a correct regex for checking email is incredibly complicated, because the rules for a valid email address as specified in the RFC are incredibly complicated.

In yours, this part (\.[az]{2,3})+ jumped out at me; the two-or-three-letters group {2,3} I often see as an attempt to validate the top-level domain, but (1) your regex allows one or more of these groups and (2) you will exclude valid email addresses from domains such as .info or .museum (Many sites reject my .us address because they thought only 3 letter domains were legal.)

My advice to reject seriously invalid addresses, while leaving the final validation to the server, is to allow basically (anything)@(anything).(anything) -- check only for an "at" and a "dot", and of course allow multiple dots.

EDIT: Example for "simple" regex

[^@]+@[^.]+(\.[^.]+)+

This matches

  • test@test.com
  • test1@test.com
  • test2@test.com
  • foo@bar.baz.co.uk
  • myname@modern.museum

And doesn't match foo@this....that

Note: Even this will reject some valid email addresses, because anything is allowed on the left of the @ - even another @ - if it's all escaped properly. But I've never seen that in 25 years of using email in Real Life.

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