Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

very loose email regular expression

I want a very loose regular expression for validating emails

Some examples:

[email protected]

Spaces will be considered invalid (including the ones at the end and the beginning), more than one @, or a dot after the @:

  1. $£"$@$£"$@kdjsad$"£$.dsad343 - valid
  2. ξδησκξδη@φδσαφδσ.φδσφ - valid (all utf-8 chars should be valid)
  3. hdjsh jdhsd.gmail.com - non valid
  4. ldksl .gmail.com - non valid
  5. dldks.gma il.com - non valid
  6. [email protected] - non valid
  7. £££τεστtest@gma!"¬ilγμαιλ.ψψομcomd**%%$ - valid

I'm trying to modify this one ^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$ but i have some troubles and your help would be appreciated.

like image 999
boom123 Avatar asked Jul 02 '26 08:07

boom123


1 Answers

You should be very careful when validating email addresses. I'm not saying you shouldn't do it, but you need to be aware that to write a 100% accurate email address validation is going to be extremely difficult and by having a not-quite perfect one, you may still be allowing invalid addresses and (worse) prevent legitimate users.

There are lots of obscure cases that are technically valid (even though they are rarely used and sooner or later are likely to break a badly written email server somewhere in the world). You need to decide whether you want to allow addresses from that minority of users.

You might have a user who has (been daft enough to get) an email address containing a quoted @ sign. e.g. "the-address-has-two-@-symbols"@example.com

Infact, you can have almost any character you can think of in the non-domain part of an address (as long as they're quoted), even spaces can appear: "Forename Surname"@example.com

In your example: £££τεστtest@gma!"¬ilγμαιλ.ψψομcomd**%%$ would actually be invalid, because domain names may only contain letters (a-z), numbers, dots and hyphens. So assuming you are doing a case-insensitive match and you do want to check for valid domain names, you should be able to simplify the expression (taken from your comment) to

^\D+([-+.']\D+)*\S[^\@]+@[a-z0-9]+[a-z0-9\-\.]*$

You can also take the domain validation further, but to do it correctly will require reading RFC 2396.

like image 171
SimonMayer Avatar answered Jul 04 '26 23:07

SimonMayer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!