简体   繁体   中英

How to prevent regex from validating double dots after @ character

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM