0

I am using the following regex to validate emails and just noticed some problems and don't see what the issue is :

/^[a-z0-9_.-]+@[a-z0-9.-]+.[a-z]{2,6}$/i.test(value)

support@tes is invalid
support@test is valid
support@test.c is invalid
support@test.co is valid

the 2,6 is for requiring and ending tld between 2 or 6 and that does not appear to be working either. I am sure I had this working properly before.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
user756659
  • 3,372
  • 13
  • 55
  • 110
  • Why use regex when you can use this => http://www.php.net/manual/en/filter.examples.validation.php – Funk Forty Niner Dec 21 '13 at 01:04
  • ...because I also replicate in jquery as needed for validation. – user756659 Dec 21 '13 at 01:06
  • Thanks and sorry for missing that. I need to replicate some regexs in jquery as I am using the jquery validation plugin for custom rules. So yes, in this case I am not using php necessarily, but I duplicate the expression in both php and jquery. – user756659 Dec 21 '13 at 01:08
  • Javascript can always be disabled by a user, therefore I recommend you also use a server-side solution as a backup ;-) – Funk Forty Niner Dec 21 '13 at 01:08
  • A valid email address can contain many many more different characters than you're allowing! – Joel L Dec 21 '13 at 01:15

4 Answers4

3

In a regex, . is a wildcard (meaning any char). you need to escape it as \.

Keep in mind though, the regex is too restrictive. You can have non-alpha numeric chars in the address, like '

Kevin Seifert
  • 3,494
  • 1
  • 18
  • 14
  • ahh... never even noticed... seems to do the trick. Regarding the ' I am marking those as invalid... a-z, A-Z, 0-9, underscore, hyphen, and period. Plus this handles subdomains. – user756659 Dec 21 '13 at 01:13
1

I notice you're not escaping the .. There might be more to it than that, but that jumps out at me.

9nonnatus
  • 152
  • 1
  • 7
  • Yes, the dot should be escaped, but failing to do so opens one to false *positives*, not false negatives. And the risk of false positives tends to be very low. This is one error people usually get away with. – Alan Moore Dec 21 '13 at 07:52
0

This is a decent check for an e-mail with Regex

 \w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

However you may want to read this. Using a regular expression to validate an email address

Community
  • 1
  • 1
tremor
  • 3,068
  • 19
  • 37
0

There are many ways to regex an email address. depending on how precise and restrictive you want it, but to re-write a working regex closest to what you have in you question. This should work:

^[\w_.-]+@[\w]+\.[\w]{2,6}$

support@tes - Invalid
support@test - Invalid
support@test.c - Invalid
support@test.co - Valid
supp34o.rt@tes.com - Valid 

But also keep in mind ALL the characters allowed in a valid email address - What characters are allowed in an email address?

Community
  • 1
  • 1
Bryan Elliott
  • 4,055
  • 2
  • 21
  • 22