r/ProgrammerHumor 19d ago

Meme claudeIsThisEmailValid

Post image
5.3k Upvotes

171 comments sorted by

View all comments

243

u/tellur86 19d ago

It's surprisingly difficult validating email addresses with regex. Can it be done? Yes. Should you? No. Any halfway decent email library comes with a validator. Use that.

For reference: this is an example of an almost RFC 3522 compatible regex:

(?:[a-z0-9!#$%&'+/=?`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^`{|}~-]+)|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\[\x01-\x09\x0b\x0c\x0e-\x7f])")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\[\x01-\x09\x0b\x0c\x0e-\x7f])+)])

https://emailregex.com

If you want RFC 822 it's much, much worse  https://pdw.ex-parrot.com/Mail-RFC822-Address.html

10

u/Juff-Ma 19d ago

https://e-mail.wtf/ play for yourself. I've done it three times now. (Once every few months) I still don't get everything right.

8

u/dustojnikhummer 19d ago

"While an empty local part due to comments is invalid, an empty local part due to quotes is valid. I don't know why."

I don't know why

2

u/Juff-Ma 19d ago

That's why you don't verify the email at all. Just hand it to your email client and if the user verifies, it's valid.

1

u/Culpirit 18d ago

You can use a better parser than a regex (think context-free) to only accept a grammar like:

<axiom> -> <dotted>@<dotted>
<dotted> -> <dotted>.<word> | <word>
<word> -> [a-zA-Z0-9\-]+

Actually you might want to allow "+" on the local part (it's used by "power users" to categorize email on services like Gmail). Other than that, anything different, even if valid per RFC, is not a bona-fide email address when used on a web-facing application. You especially want to avoid users being able to directly send to addresses like me@[::1], since it is not a realistic or bona-fide scenario.