0

I have a few requirements to validate email address and have a few regex expressions for that purpose. But how I can combine them to one regex to make it work correctly?

(?=^\\S+@\\S+\\.\\S+$)

Dotted email address

(?=^[A-Za-z0-9@$\\._-]+$)

allows alphanumeric, '@', '.', '_', '-'

(?=^[A-Za-z0-9].*$)

cannot start with special character

(?=^.{5,100}$)

between 5 and 100 characters

(?=^((?!([0-9]{9,}\\1)).)*$)

Not nine or more numbers

(^(?!.*[@].*[@]).*$)

One at mark

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Yurii
  • 3
  • 2
  • Did you try concatenating the expressions? – Christian May 27 '21 at 08:11
  • "*allows alphanumeric, '@', '.', '_', '-'*" therefore, it disallows valid characters like `+` or Cyrillic or Chinese, or umlauts, or other non-Latin characters. "*between 5 and 100 characters*" it's odd to put a lower bound here `a@b.c` is five characters. If any of these is removed, it's not going to be valid due to the other rules. The upper limit is also unneeded - sure not a lot of addresses use it doesn't seem like a good reason to limit this. [This is the real maximum](https://stackoverflow.com/a/574698/). "*Not nine or more numbers*" very weird validation rule. – VLAZ May 27 '21 at 08:35
  • 1
    Why all this trouble and not just ``? – Niet the Dark Absol May 27 '21 at 10:00
  • @NiettheDarkAbsol dunno. There are many, many developers who seem to be at war with legitimate emails and simply do not want to accept them. Only *their* interpretation of what an email should be even if their interpretation has no real bearing on how any part of their application works. It's like requiring the user to stand on one foot while clicking a button - only serves to dictate how a user should behave without this being needed or having any impact. – VLAZ May 28 '21 at 07:33

2 Answers2

0

Try concatenating your expressions:

const emailRegex = /(?=^\S+@\S+\.\S+$)(?=^[A-Za-z0-9@$\._-]+$)(?=^[A-Za-z0-9].*$)(?=^.{5,100}$)(?=^((?!([0-9]{9,}\1)).)*$)(^(?!.[@].[@]).*$)/;
Christian
  • 7,433
  • 4
  • 36
  • 61
0

There are a lot of custom rules using lookaheads, from which you can omit a few by matching instead of asserting.

^(?=\S{5,100}$)(?!\S*\d{9})[A-Za-z0-9][A-Za-z0-9$\\._-]*@[A-Za-z0-9$\\._-]+\.[A-Za-z0-9]+$
  • ^ Start of string
  • (?=\S{5,100}$) Assert 5-100 non whitspace chars
  • (?!\S*\d{9}) Assert not 9 consecutive digits in the string
  • [A-Za-z0-9] Match a single char A-Z a-z or a digit
  • [A-Za-z0-9$\\._-]* Optionally repeat what is listed in the character class
  • @ Match an @ char (Note that you can omit the square brackets [@])
  • [A-Za-z0-9$\\._-]+ Match 1+ times any of the listed in the character class
  • \.[A-Za-z0-9]+ Match a . and 1+ times any of the listed in the character class
  • $ End of string

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70