56 comments

[ 3.9 ms ] story [ 214 ms ] thread
When is this needed? A one line regex can't get you far enough here?
Unless you are providing a user with an email account and need to ensure it's 100% valid, it's not worth doing anything but the most trivial validation. It's far better to allow an invalid email to be entered than disallow a valid one. The real validation is sending an email to it and the user opening that link. If they managed that, then it's a valid email.
How about tiered validation:

1. I'll let you pass no questions asked:

* gotta have that '@' sign

* left of '@' sign must have greater than zero characters-- a-z, 0-9, dots are cool, plus whatever the rules are for international characters

* right of '@' whatever the rules are for domains

2. Pay me $1.99 through stripe to continue whatever you're trying to do, every time you're trying to do it:

* you've got double quotes, spaces, or other "actually, emails can contain..." bullshit in the local part of the addy

"Mastering Regular Expressions" from O'Reilly covers regular expressions to validate email. The resulting regular expression is dozens of lines long.

Consider RFC 3696, "Application Techniques for Checking and Transformation of Names". The author provides some example valid email addresses:

    Abc\@def@example.com
    Fred\ Bloggs@example.com
    Joe.\\Blow@example.com
    "Abc@def"@example.com
    "Fred Bloggs"@example.com
    customer/department=shipping@example.com
    $A12345@example.com
    !def!xyz%abc@example.com
A one line regular expression won't do much but block valid users. As has been said often in this thread, the best way to validate an email is to send to the address and confirm delivery through user interaction. Everything else is half-measures, often doing more harm than good.
Interesting list, and I'm surprised by most of them, but part of the reason for that is that literally no-one uses email addresses like that.
I have seen addresses like at least 4 of the 8 in the wild in recent memory, tho to be fair it may be longer than 10 years for #8 (not many folks use UUCP for email any more).

"I haven't seen" != "no-one uses".

The first three aren’t valid. As far as I can tell, RFC 3696 accidentally invented unquoted escaping there, which is not permitted by RFC 822, 2822 or 5322.

The errata are a doozy <https://www.rfc-editor.org/errata/rfc3696>, with a bad correction verified, a bad correction of that correction verified, and a reversion of the two incorrect corrections with incomplete justification (not quite mentioning the root cause, that you can’t actually use backslash-escaping outside a quoted-string like the RFC deliberately did) “held for document update” (which I suspect means that the reviewer finally realised the actual error, and decided it was too large to deal with with this way, but there are no verifier notes and I don’t know where the errata discussion records are, if they’re even public).

I wrote more, but it becomes all messy and confusing and I think I just discovered that according to RFC 2822’s and RFC 5322’s grammars, a space inside a quoted-string would actually need escaping, which would ruin "Fredd Bloggs"@example.com, which is widely understood to be valid. (This is because qtext lacks %d32 (space), which I think is accidental but it’s not entirely clear—it’s all bound up in the painful question of whether space is printable or not; see also <https://www.rfc-editor.org/errata/eid4692>. But their intent was clearly for space not to need escaping, as various examples all over the place use spaces unescaped in quoted-strings.)

So… I’m going to tip-toe gently away now and stop thinking about email address syntax for the rest of the day if I can help it.

As someone who uses an email address in the form of <word>@<numeral>.<word>, I can tell you from lots of experience that entirely too many devs in the world thought "can't we just" and got it horribly wrong.
This is the first result in Google for "regex for email validation" and it validates your email format correctly

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

You can have a one line regex that validates email that are correct according to RFC. However, most popular email services don't care about that. A lot of "valid" (as in active emails on email service like Gmail) are not "RFC valid", some "RFC valid" emails are not valid to many email services and MTAs.

Realistically, trying to validate email if you aren't in the business of providing an email service is a fool's errand that doesn't bring much to the table.

Nope, you can't. Email address are not defined with a regular language, so they provably can't be validated with a regular expression no matter how long.
I would advise against doing anything more than checking for an @... and, I guess, at least one character on either side of that. Just send a verification link in an email instead.

(The fact that an email address is syntactically valid is a matter for SMTP/MTA implementers and syntactic validity doesn't mean that an email address actually receives mail.)

Exactly right. I'm so tired of systems that don't work with my .email domain or have rules that ".com" can't be on the left side of the @. We should be beyond this by now.
This library will actually check DNS records to validate domains, so any TLD the server can reach will work with this library.

It also has a thresholding system to allow you to pick how quirky the email addresses (and therefore, how full of typos) that you accept can be. You can set it up to accept RFC5322 addresses and tolerate up to certain levels of errors.

The default is just "valid syntax", but DNS lookups and domains that violate the SMTP spec are tolerated if you use the (demonstrated) ISEMAIL_THRESHOLD check.

I think this is the best email address validator I've seen. It sticks to the standards, at least those relevant when the software was last maintained, and doesn't do anything silly like regex checking.

Validating through a mail server that just tries to send an email and hopes nobody made a typo is a burden on most users (typos are easy to make and weird email addresses should show a warning, though only completely invalid addresses should show an error) and can even lead to IP reputation damage for the mail server.

(comment deleted)
terrible documentation. the only real way to check an email address ia to send a mail to that address and get a response back. maybe this does that, but the documentation does not say so.
(comment deleted)

    define('ISEMAIL_STRING_AT'  , '@');
    define('ISEMAIL_STRING_BACKSLASH' , '\\');
    define('ISEMAIL_STRING_DOT'  , '.');
    define('ISEMAIL_STRING_DQUOTE'  , '"');
    define('ISEMAIL_STRING_OPENPARENTHESIS' , '(');
    define('ISEMAIL_STRING_CLOSEPARENTHESIS', ')');
I find it hard to believe people seriously still do this. This is satire, right?
It looks like that's auto generated
That's because you're not thinking of the future when the @ symbol might change.
Yes but defining it like this does not help much in avoidong future refactoring. The value should be loaded from a property file and/or environment variable at least
That's absurd, you're just asking for failure unless you load it from a dedicated high,-availability microservice built on a dedicated cloud non-relational key-value store.
This doesn't seem too odd to me when considering it may be a convention of writing a lexer. E.g. symbols defined not just one-to-one with ASCII characters, but may also include something like DOUBLE_EQUALS, STRING_LITERAL, NUMBER_LITERAL, etc.
And in fact...

    define('ISEMAIL_STRING_DOUBLECOLON' , '::');
    define('ISEMAIL_STRING_IPV6TAG'  , 'IPv6:');
This is very typical for parsers (characters) and compilers (machine/bytecode).

You could do it with namespaces and `const` though to be less verbose.

I genuinely find this useful, in scenarios where filters and regexes are likely to devolve into punctuation explosions otherwise.
Does not seem to allow for domains with AAAA but neither A nor MX. Tut!
To be fair, this was written seven years ago and IPv6 has grown quite significantly since then. Even today IPv6-only mail hosts probably miss a lot of important email.

However, ISEMAIL_DNSWARN_NO_RECORD is defined as 6, still lower than the ISEMAIL_THRESHOLD (16) used to indicate a warning rather than an error.

Am I not getting something or why is this interesting? Some random 7 year old PHP library, cool?
I believe the subtext is that "proper" validation of an email is deceptively complex when you would expect a single regex to do. I can't really vouch for if that assumption holds or not.
If there are any lessons to be had here, this one is certainly amongst them.
Yes. And not much point in all that careful checking against the RFCs - many email servers use, accept, and correctly process email addressed to technically invalid addresses.

This library runs the risk of blocking actual, working email addresses.

The code itself is very helpful and interesting, https://github.com/dominicsayers/isemail/blob/master/is_emai....

Point is that checking whether something is a valid email or not is 1179 lines long (I know there are a lot of comments). Particularly interesting is to look at all of the possible error conditions, and the fact that "whether a string is an email address" is not so much a binary yes-no, but the library provides a "likeliness threshold" option.

Essentially just pointing out that checking if a string is/can be an email address is surprisingly complex.

O PHP! The language where it's difficult to discern between genius and madness.
I hate when validation libraries have a bug and you look like a moron in front of your boss. Honestly, simplicity is the best policy and the next best policy is letting your email provider sort out the rest.
May conflict with the wordpress php function is_email(). [1]

  According to W3Techs, WordPress powers 43% of all the
  websites on the Internet, including those without a
  content management system (CMS) or with a custom-coded
  CMS. Or to put it another way, WordPress powers over
  one-third of the web! And if you limit the data set
  to only websites with a known CMS, WordPress’ market
  share gets even more dominant.

  In that case, WordPress holds a 65% market share
  for content management systems on websites with a
  known CMS. 
[1] https://kinsta.com/wordpress-market-share/

  if ($email =~ /@/) { ... }
This is my way, too. Anything more complex is not worth it in many (not all) use cases.
Email regex: (.*)@(.*)

If you need anything more specific the best bet is to try send an email to it.

I would filter out at least whitespaces and comma. Aside from catching typos this also protects against header injection or spam abusenby sending to multiple recipients.

And yes, those should be defended when constructing the mail, but checking early doesn't cost much.

I do almost exactly that, but I replace the stars with plus. I don't think empty name or domain parts are legal?
Should be /^[^@]+@[^@]+$/ at least, because you need something before and after @
It's allowed to have @ as part of the local part if it's quoted. So that wouldn't match my email `"foo@bar"@example.org`
Breasts with a chest tattoo.
I’m not sure how I feel about the source code. The file is meticulously organized and absolutely chock full of comments. But I struggle to follow the control flow at all.

Maybe if I spent more time with that style, it would click for me?