문제

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

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top