2

I am using the following regex in a js

^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$

This validates email in subdomain (ex: myname@google.co.in) Unfortunately a double dot is also validated as true, such as

myname@..in
myname@domain..in

I understand the part @[a-zA-Z0-9.-] is to be modified but kinda struck. What is the best way to proceed.

TIA

KuKeC
  • 4,392
  • 5
  • 31
  • 60
Jagadeesh J
  • 1,211
  • 3
  • 11
  • 16
  • Your e-mail validation regex is incorrect, and it’s [hard to write correct ones](https://tools.ietf.org/html/rfc5322#section-3.4.1), so try to use something pre-built. https://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address – Ry- Nov 30 '15 at 08:22
  • Please reconsider accepted answer, the one you accepted is not doing what is required. – Wiktor Stribiżew May 11 '23 at 07:11

2 Answers2

4

Try using:

^([\w+-]+\.)*[\w+-]+@([\w+-]+\.)*[\w+-]+\.[a-zA-Z]{2,4}$

I've replaced the [a-zA-Z0-9_] with the exact equivalent \w in the char group.

Note that in the regex language the dot . is a special char that matches everything (but newlines). So to match a literal dot you need to escape it \..

Legenda:

  • ^ start of the string
  • ([\w+-]+\.)* zero or more regex words (in addiction to plus + and minus-) composed by 1 or more chars followed by a literal dot \.
  • [\w+-]+ regex words (plus [+-]) of 1 or more chars
  • @ literal char
  • ([\w+-]+\.)*[\w+-]+ same sequence as above
  • \.[a-zA-Z]{2,4} literal dot followed by a sequence of lowercase or uppercase char with a length between 2 and 4 chars.
  • $ end of the string
Giuseppe Ricupero
  • 6,134
  • 3
  • 23
  • 32
-1

Try this:

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

You can test it here - https://regex101.com/r/Ihj8sd/1

Andrew Evt
  • 3,613
  • 1
  • 19
  • 35
  • You regex is equivalent to ``^(.+)(@.+)(.[a-zA-Z]{2.4}){2,}$``. Escape the dot ``.``, as is it doesn't matches **only** the literal dot (it matches everything now, making the other chars in the groups redundant). Also why so much unused capturing groups? Watch the [demo](https://regex101.com/r/yR2yQ5/1) As is it doesn't solve the OP problem... – Giuseppe Ricupero Nov 30 '15 at 09:46
  • 1
    This regex does not actually require a dot after `@`. – Wiktor Stribiżew Mar 04 '21 at 13:12