Regex for email validation Not Allow all number for a part

Viewed 142

I have problem with regex for model email validation, I using this code:

^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$ --> (https://emailregex.com/)

I will modify become:

123@123.com --> invalid(if before @ all number or after @ all number)
123a@123a.com --> valid(if before @ must combine string or only string and after @ combine string or only string)

Anybody improve my code, thanks a lot.

1 Answers

Adding negative lookahead to your regex should do it:

const regex = /^(?!\d+@)\w+([-+.']\w+)*@(?!\d+\.)\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
[ 'a@b.com',
  'a123@b123.com',
  '123@b.com',
  'a@123.com'
].forEach(str => {
  console.log(str + ' ==> ' + regex.test(str));
});

Output:

a@b.com ==> true
a123@b123.com ==> true
123@b.com ==> false
a@123.com ==> false

Explanation:

  • first lookahead ^(?!\d+@): not 1+ digits from start to @
  • second lookahead @(?!\d+\.): not 1+ digits from @ to next dot
  • you could add additional lookaheads for the punctuation & word sequence after that if needed
Related