0

I want to allow a single quote in email while doing the javascript email validation.

I have used the following code but it's working as expected.

 var pattern = new RegExp(/^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/);
 return pattern.test(emailAddress);

Following emails it should return as valid

 zoe.o’hara@test.com 
 natalie.o'sullivan@test.co.in
mcky
  • 823
  • 2
  • 7
  • 20
Rober
  • 73
  • 1
  • 8
  • 1
    Email validation is actually something regex is not that good at, this link has a more robust version you could try => https://emailregex.com/ the perl version looks terrifying.. – Keith Jul 22 '22 at 09:35
  • Does this answer your question? [How can I validate an email address using a regular expression?](https://stackoverflow.com/questions/201323/how-can-i-validate-an-email-address-using-a-regular-expression) – Liam Jul 22 '22 at 09:37

1 Answers1

1

Just need to add ' and to the first character class

Changing: [a-zA-Z0-9_\-\.] to [a-zA-Z0-9_\-\.'’]

Fixed:

var pattern = new RegExp(/^([a-zA-Z0-9_\-\.'’]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/);
return pattern.test(emailAddress);

Do be aware of Keith's comment. There is more info in a question here.

mcky
  • 823
  • 2
  • 7
  • 20