Question

Please read the requirement before thinking it is duplicate of any similar question.

As far as I found more than 20 Email validation regular expressions But all of them allows

a@a.co.in.in.in.in.in.in.in

as valid email address!!!

I want to restrict that only two dots(.) should be allowed.

For Example:

Valid Emails

somename@yahoo.in

somename@yahoo.co.in

somename@somesite.bizz

somename@gmail.com

somename@somesite.net

Invalid Emails

@.co

@a.com

a@a

a@.com

a@a.co.in.in //maximum two dots allowed otherwise invalid

a@a.co.in.in.in.in.in.in //maximum two dots allowed otherwise invalid

For this I tried with

[a-zA-Z0-9._%+-]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,5}[\.[a-zA-Z]{2,5}]{0,1}

It is working with 2 dots but throwing invalid message for

somename@somesite.com

Was it helpful?

Solution

I think that it should be like

[a-zA-Z0-9._%+-]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,5}(\.[a-zA-Z]{2,5}){0,1}

I'm not experienced in regex, but I think that [.[a-zA-Z]{2,5}] is considered character group. Parentheses do the trick.

OTHER TIPS

One possible approach is to first validate with one of the existing regular expressions that allows the email address a@a.co.in.in.in.in.in.in.in. If it validates, then do the following steps.

  1. Do a String split on the @ sign.
  2. Take the right hand side of the split, and do a split on the period .
  3. If the resulting array has length 2 or 3, then you have found a domain that satisfies your definition of a valid email. If not, then reject.

This way, you let regex you already found handle the grunt work, and you just check for the one additional condition you care about.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top