0

I need a regex that will check (if email is like a@b.cc:

  • email must have @ and . (must have both). I refer to the whole string that must contain @ and at least one dot.

  • 1st word of email must have 1+ char

  • the domain name between @ and . must be 1+ char

  • TLD must be 2+ char

I made regex like .+@.+\. but it's not the one, I know. I am bad in regex as I use it so rarely.

Can anyone help me?

sandalone
  • 41,141
  • 63
  • 222
  • 338

1 Answers1

1

It's not clear if you are matching an email in the middle of a paragraph of text, or matching an already extracted string. I am assuming the latter, and anchoring the match to start and end of line...

/^.+@.+\.[^.]{2,}$/

regex railroads

p.s. using regex to validate emails is complex: http://www.regular-expressions.info/email.html

Billy Moon
  • 57,113
  • 24
  • 136
  • 237
  • Just regular email a user gives during signup. Local validation. – sandalone Sep 22 '16 at 15:02
  • your regex is basically useless. it matches `@@@@@@@.@@` for example – Bohemian Sep 22 '16 at 15:18
  • @Bohemian yep - question does not specify that as being a problem. As indicated in footer note, email validation is complex. I remember using angular js email validation in Ireland, and it does not allow `'` in a name, so that was a good chunk of people's emails not working. The more situations you account for, the more complex the regex becomes until it's so complex you want to go back to something simple again. Also, what is not valid or infeasible email today, might become valid tomorrow. There is a section about trade-offs in the link I sent. – Billy Moon Sep 22 '16 at 15:22
  • @Bohemian I'd argue that any validation more complex than this is basically useless. It wouldn't be if it wasn't for the fact that seemingly everyone gets it wrong. As a matter of fact, even this one will fail on a legitimate email like "bob@localdomain" since it expects a TLD but I'd call that acceptable because in the vast majority of cases, it's external emails that one works with. – VLAZ Sep 22 '16 at 15:39
  • @vlaz what about bobby@154.233.153.1 which is also ok email I think, or perhaps IPv6? – Billy Moon Sep 22 '16 at 15:41
  • @BillyMoon yep, that's also going to be rejected but...you know - it's not _really_ that common to use those. Same with the domains without a TLD. But the my ideal validation `.+@.+`. That should be enough to catch most gross mistakes. Then a soft validation can be done for the domain part - `.+\..+` (or `[^.]+\.[^.]+) to check if it has a TLD and if not, just mention it to the user "Are you sure that is correct and you want to use this email?". But that's about as hard I'd like to go on email validation via regex. Just send an email to confirm it afterwards. – VLAZ Sep 22 '16 at 15:49
  • @vlaz I agree with `.+@.+` and the key point that the validation should be used to inform the user, and not to prevent form submission. – Billy Moon Sep 22 '16 at 15:56