简体   繁体   中英

unrecognizable email address from javascript validation

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;
  }
}

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}$/);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM