简体   繁体   中英

Regex for email validation in Redux form

I'm trying to build a regex for email validation, i have additional several conditions to check:

  1. allowed: uppercase and lowercase English letters, digits 0 to 9

  2. allowed: "_", "-", “.”, “@” and "'";

3.a. Character "." is allowed to be provided if it is not the first or last character

3.b. "." does not appear two or more times consecutively

3.c. "." must appear at least one time in domain name

  1. should not contain “.@” or “@.”

  2. should not start with "."

  3. “@” must appear once

  4. In the domain name, the string length, after last “.” , should have at least 2 characters

  5. Leading "_" is not allowed in the domain name

I have created the following regex:

^[a-zA-Z0-9_'-]{1}[a-zA-Z0-9._'-]*([^.]@[^._])([a-zA-Z0-9_.'-])+[.]{1}[a-zA-Z0-9_'-]{2,}$ 

I'ts covered all the sections exclude section 3.b.

example for valid email: ya.ll.tj@gg.cc example for invalid email: ya..lf@dd.cc , yssss...@kk.dd

Thank's

At the beginning of the pattern, negative lookahead for .*\\.{2} to ensure that there are never two . s in a row:

(?!.*\.{2})

There are also some fixes and optimizations to make. By using negative lookahead for (a single) . at the start of the string, you can keep from having to repeat the character set twice (since the first is identical to the second, only without a . ).

Negative character sets alone can match any character not in the set - for example, your [^.] right before @ can match a newline character, which surely isn't desirable. Instead, to ensure that the last character before the @ isn't a . , use another character set:

^(?!.*\.{2})(?!\.)[a-z0-9_.'-]*[a-z0-9_'-]@

(in modern environments, you could negative lookbehind for . at the @ instead, similar to the first technique, to avoid having to repeat the similar character set, but JS lookbehind isn't supported everywhere yet)

Use the case-insensitive flag as well, to avoid having to use [a-zA-Z everywhere. In full:

^(?!.*\.{2})(?!\.)[a-z0-9_.'-]*[a-z0-9_'-]@(?!_)(?:[a-z0-9_'-]+\.)+[a-z0-9_'-]{2,}$

https://regex101.com/r/tZ7LHt/2

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