3

This is a regular expression I found online that seems to do a great job at simple email address validation. The problem is it doesn't allow + in the email, like my+email@domain.com. I'm not great at regex, so how can I add support for a + without breaking the whole thing?

var regex = new RegExp( /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i );
Gavin
  • 7,544
  • 4
  • 52
  • 72

2 Answers2

6

Change the second [\w-]+ to [+\w-]+

Michael Ward
  • 496
  • 5
  • 13
  • Thank you for the fast reply! You correctly answered my question based on my example. I'll mark as accepted once the time limit is up. One thing I forgot though is that it's valid for the `+` to be the first character also. I also changed the first `[\w-]+` to `[+\w-]+` and that seems to allow `+` as the first character as well. Is that the correct way to do this? – Gavin Jun 07 '18 at 18:22
  • 1
    Yep! Good catch too! – Michael Ward Jun 07 '18 at 19:04
0
([+\w0-9._-]+@[\w0-9._-]+\.[\w0-9_-]+)
user2643679
  • 706
  • 12
  • 18
  • 1
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. You can find more information on how to write good answers in the help center: https://stackoverflow.com/help/how-to-answer . Good luck – nima Oct 01 '21 at 06:55