I'm trying to build a regex for email validation, i have additional several conditions to check:
allowed: uppercase and lowercase English letters, digits 0 to 9
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
should not contain “.@” or “@.”
should not start with "."
“@” must appear once
In the domain name, the string length, after last “.” , should have at least 2 characters
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.t.j@gg.cc
example for invalid email: ya..l.f@dd.cc , y.s.sss...@kk.dd
Thank's
Answer
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
No comments:
Post a Comment