0

I have a script written long ago by a freelancer that's worked fine until now. The script simply checks the email address from a form against some matching rules and returns true/false. Problem is for some reason it isn't recognizing an email address that has a very simple firstInitialLastName@domain.com syntax (no extra periods or characters, etc).

I don't understand javascript as well as I understand PHP so if someone could tell me why this script would return false against an email address formatted like I indicated above, I'd greatly appreciate it.

function check_email(str) {
  var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
  if (!str.match(re)) {
    return false;
  } else {
    return true;
  }
}
  • 3
    It's wrong in so many ways and needs updating. Use the one found here: http://stackoverflow.com/questions/46155/validate-email-address-in-javascript – Shane Garelja Feb 17 '11 at 20:42
  • 1
    also, this could be refactored to `return str.match(re)`. Save your carpel tunnel 'til you're older. – Brad Christie Feb 17 '11 at 20:44
  • @Shane which one? there are tons on that question. – Stephan Hovnanian Feb 17 '11 at 20:58
  • @Stephan - Sorry :) The one with the highest score - at the top. – Shane Garelja Feb 17 '11 at 21:00
  • ah, thanks :) hope it will work...the code highlighting in Dreamweaver when I pasted it in seems to be strange-looking. Maybe because of one of the quotes. I assume I need a semicolon at the end of each line? (like I said, I don't love javascript mostly because of the syntax...PHP is a lot friendlier) – Stephan Hovnanian Feb 17 '11 at 21:08

1 Answers1

0

It should work, the RegExp is valid.

Are you sure your email is trimmed of spaces at the end/beginning? if somebody will leave a trailing space at the end or hanging one at the beginning it won't work as it accepts only alphanumeric characters at the beginning and a-zA-Z characters at the end (domain). Whitespace is the only thing I can come with that can break it.

And you could refactor it a bit and shorten to simply return the match value as it returns array of matches or null (which equals to false in comparisions)

function check_email(str) {
    return str.match(/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/);
}
Tom Tu
  • 9,573
  • 35
  • 37