1

I have the following email validation regex in JavaScript. It doesn't actually return anything, but I think it should (true or false).

What's wrong with this code?

function isEmail(aa){
    var testx=/^([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22))*\x40([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d))*$/
    return testx.test(aa);
}

<input type="text" name="email" id="email" onChange="isEmail(this.value)">
Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
Ghozt
  • 267
  • 4
  • 13
  • 1
    `return testx.test(aa)` <- variable not string – elclanrs May 07 '13 at 10:35
  • 5
    Do you think you'll maintain this regex ? You should read [this](http://davidcel.is/blog/2012/09/06/stop-validating-email-addresses-with-regex/). – Denys Séguret May 07 '13 at 10:35
  • `onchange="return isEmail(this.value)"` - except I don't think you can cancel an onchange event. What do you expect to actually happen if the entered value fails the validation? – nnnnnn May 07 '13 at 10:37
  • @Ghozt I think it'd be helpful for everyone if you broke the regex out into mulitple lines and tell us what you think each line should do, instead of dumping a regex that's hard to follow on others. – George Stocker May 07 '13 at 11:12
  • +1 @dystroy, nice article ! :) – Andrea Ligios May 07 '13 at 12:09
  • See also [this question](http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address) for more regex suggestions. – legoscia May 07 '13 at 12:32

2 Answers2

1

you're testing for string 'aa', change

return testx.test('aa');

to

return testx.test(aa);

See: jsFiddle Demo

Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
0

Email validation via regular expressions seems to be extremely complicated.

If possible you should use HTML5 form validation

<input type="email">

diveintohtml5.info is a good place to learn more about form validation.

As far as I know the validation is a browser side thing that only works togehter with sumbit buttons. There is no javascript api for checking if a specific string is valid.

Tim Bartsch
  • 918
  • 8
  • 18