Elshan
Elshan

Reputation: 7683

Validate email address with multi level domains in PHP with RegEx

Need to validate email address with single domain level or multi level domains.(actually domain level <=4)

Criteria:

Ex: [email protected]

above example there 4 domains;

I try with this RegEx:

^[a-zA-Z](:?[a-zA-Z0-9._-])+(@[a-zA-Z]+[a-zA-Z0-9_-])+\.+(([a-zA-Z]){2,6})$

But above regex not validating multiple domains correctly.It's only get 1 domain. Ex: [email protected]

Online Regex : https://regex101.com/r/7SXS1Z/1

Upvotes: 1

Views: 1805

Answers (2)

Jan
Jan

Reputation: 43169

Maybe this is what you're looking for

^
[a-zA-Z][-.\w]*       # before @
@
[a-zA-Z][-.\w]+       # first subdomain
(?:
    \.[a-zA-Z][-.\w]+ # eventually others
){1,3}
$

See a demo on regex101.com.

Upvotes: 1

revo
revo

Reputation: 48711

Your regex applies much more rules in accepting an email address. E.g. allowing email addresses to include more than one @ symbol. Go as simple as your own rules:

^[a-z][^@]*@(([a-z][a-z0-9-]+)\.){0,3}(?2)$

Live demo

Upvotes: 1

Related Questions