-1

Email validation expression \w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* allows empty spaces, but otherwise works perfectly.

It does not fail the following email address:

john doe@hp.edu

How can I restrict this to not allow whitespaces?

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
user3467905
  • 11
  • 1
  • 1
  • 1
  • Don't try to validate email addresses with regex. The standard is just too complex. [Here](http://ex-parrot.com/~pdw/Mail-RFC822-Address.html) is an example of how much regex is needed (and it doesn't even fulfill the *whole* standard). In what context are you doing this? I recommend using a module of some kind, as there are plenty of those that do it right. – Biffen Mar 27 '14 at 11:20
  • I am using it while saving person record .if user enters invalid email address it gives validation error .and while validating that control I am using this regex. – user3467905 Mar 27 '14 at 12:03
  • That wasn't much of an answer. I understand that you are trying to validate email addresses. I'm just saying that regex is not a very good tool for the job. There are modules for most programming languages that do it for you, I recommend using one of those. – Biffen Mar 27 '14 at 12:15

1 Answers1

1

Some APIs have functionality to match on the entire string, where-as with others it would always search anywhere in the string.

If it's the latter case, it won't fail because a substring, specifically doe@hp.edu, matches the pattern.

To fix this, you could either check if the API you're using has a function to match on the entire string, or you could add ^ to the start and $ to the end of your pattern, indicating the start and end of string / line respectively.

^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
  • Thanks Dukeling...trying this solved the whitespaces problem but there comes another ,it fails the single letter domain email addresses like doe@m.tk – user3467905 Mar 27 '14 at 11:58
  • @user3467905 - https://regex101.com/ tests out fine for single letter domain and this reg expression as per Bernhard Baker's answer. i.e. 1 Match – Allan F Jun 28 '21 at 05:21