-3
var re = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/;
var email = document.forms["checkout"]["email"].value;
if (re.test(email.value)) {
    return true;
} else {
    alert("Invalid email address");
    return false;
}

I have tried quite a few email regex suggestions on this site but when the function is called it always throws the alert. Not even simple email address are coming back valid. What am I doing wrong?

Gwenc37
  • 2,064
  • 7
  • 18
  • 22
  • 1
    Just use `^.+@.+\..+$`. What you have fails https://emailtester.pieterhordijk.com/test-pattern/MzA5 – PeeHaa May 30 '14 at 11:46
  • Not really duplicate @Goving, he is not asking for help in that sense, what does not work here is the code itself, despite of the quality of the email verification or the regular expression. – miguel-svq May 30 '14 at 12:04

3 Answers3

1

The regex is valid but I'll get to this in a moment. First of all, you must have extra characters in that field or something like that - running your code in the JS console in the console worked with just setting the email manually.

Now the more important part - do not use that regex to check for emails - I second @PeeHaa's suggestion of ^.+@.+\..+$ - it's simple and works well enough. Yours constricts the user too much, for example, nobody can use an email from a .info domain because they can only have 2 or 3 characters at the end. As another example, a user cannot use + in an email, which is valid (Gmail uses to great effect). And the third thing glaringly wrong with it is it cannot handle non-English names - domains in, say, Cyrillic exist, too.

If you are setting email to be the field.value property, then try to take email.value which would return undefined

VLAZ
  • 26,331
  • 9
  • 49
  • 67
0
var email = document.forms["checkout"]["email"].value;
if (re.test(email.value)) {

one of them is wrong (I think)

var email=......value and then if(re.test(email.value

miguel-svq
  • 2,136
  • 9
  • 11
-1

Please use below code:

 /* this function is use to check email format and prompt user if it's not correct */
    function IsValidEmailAddress(emailAddress) {
        var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
        return pattern.test(emailAddress);
    }
Systematix Infotech
  • 2,345
  • 1
  • 14
  • 31