3gwebtrain
3gwebtrain

Reputation: 15303

validating an email with regexp multiple conditions

I am looking for a valid regexp for my email validation requirement. I tried several times, but it buggy.

here is my try: .*@[^\W_]+(?:[\w-]*[^\W_])

need to fit with:

xxx@_domain.com => invalid @ starts with _
xxx@domain_.com => invalid domain ends with _ 
[email protected] => invalid @ starts with - ( hypen)
[email protected] => invlaid domain ends with - (hypen)
[email protected] => invalid domain start with - (hypen)
[email protected] => invalid domain only contains numbers
[email protected] => valid domain contains both number and chars
[email protected] => valid
[email protected] => valid
[email protected] => valid
[email protected] =>
xxx@abc_efg.com =>  valid _ inside the chars
[email protected] => valid _ start with 

any one help me?

Upvotes: 1

Views: 230

Answers (2)

The fourth bird
The fourth bird

Reputation: 163342

For your specific requirements you might use

^\w+(?:[_-][^\W_]+)*@(?![\d._-]+\.[^\W_]+$)[^\W_]+(?:[_-][^\W_]+)*\.[^\W_]{2,3}$

Explanation

  • ^ Start of string
  • \w+ Match 1+ word chars
  • (?:[_-][^\W_]+)* Repeat 0+ times matching - or - and 1+ word chars except _
  • @ Match literally
  • (?! Negative lookahead, assert what is on the right is not
    • [\d._-]+\.[^\W_]+$ Assert only digits or any of ._- until the end of the string
  • ) Close lookahead
  • [^\W_]+ Match 1+ times a word char except _
  • (?:[_-][^\W_]+)* Repeat 0+ times matching - or - and 1+ word chars except _
  • \.[^\W_]{2,3} Match . and 2-3 times a word char except _
  • $ End of string

Regex demo

Upvotes: 1

Breno Prata
Breno Prata

Reputation: 732

If this email value comes from a HTML input, i think the best way is to just set the type property to email and let the browser do the hard work, but if this is not the case, you can check Regexr, there's some community regex already created and it's quite a useful tool

Upvotes: 1

Related Questions