0

I have a regular expression to validate an email address. It supports trailing and leading spaces, since I want to allow users to make that mistake, I'll just trim the email value on the backend. This logic is exactly what I want.

This is the regular expression I have right now: \s*[-+.'\w]+@[-.\w]+\.[-.\w]+\s*

However, my current expression also allows ``` and , characters in the email address. How can I make sure that only characters valid for an email address are supported, but also allow trailing or leading spaces?

So these addresses are currently allowed, which I don't want:

dfdfd@bcvb.com,
dfdfd@bcvb.com`
Adam
  • 6,041
  • 36
  • 120
  • 208

1 Answers1

1

you can try out the regex

^(?!['`])\s*[-+.'\w]+@[-.\w]+\.[-.\w]+\s*$

see the demo here or use the regex

^(?=[\w\s-+.])\s*[-+.'\w]+@[-.\w]+\.[-.\w]+\s*$

demo

marvel308
  • 10,288
  • 1
  • 21
  • 32
  • Thank you! It however also accepts this email address as valid: `'d@dfgdfg.com`, I can remove `'` from the regex (I know it was in my original one too), but email address never have that character right? – Adam Aug 19 '17 at 21:57
  • please check out the updated demo and regex – marvel308 Aug 19 '17 at 22:00
  • add all invalid characters in the square brackets in (?!['`]) – marvel308 Aug 19 '17 at 22:01
  • Thanks. But is there no way to do it the other way around? Instead of having to define all non-allowed chars, define the chars that ARE allowed? I mean: `[a-zA-Z0-9._-+]` (anything else?)...isn't that a shorter way to do it? – Adam Aug 19 '17 at 22:15
  • yes try ^(?=[\w\s])\s*[-+.'\w]+@[-.\w]+\.[-.\w]+\s*$ – marvel308 Aug 19 '17 at 22:17
  • add everything allowed in the square bracket in (?=[\w\s]) – marvel308 Aug 19 '17 at 22:19
  • One last thing: a lot of users enter the wrong TLD: ".con" instead of ".com". How would I specifically disallow ".con" as the TLD? – Adam Aug 20 '17 at 00:58