[thelist] Email Validator

Matthew Blanchard blanchardmatthew at hotmail.com
Wed Dec 5 08:54:52 CST 2001


From: "Lachlan Cannon" <tiedefenderdelta6 at yahoo.com>
Subject: [thelist] Email Validator


> here is my solution to the problem (it can be spoofed, but
> it's more difficult than the other one. I've checked it and
> it worked in IE6, NS6, and Op5, if anyone finds a bug or
> has an improvement, please tell me)
>
> var pattern=/(^[
>
\-_\.a-zA-Z0-9]+)@((([0-9]{1,3}\.){3}([0-9]{1,3})((:[0-9])*))|(([a-zA-Z0-9\-
]+)(\.[a-zA-Z]{2,})+(\.[a-zA-Z]{2})?((:[0-9])*)))/;

I think a less restrictive pattern is better (like darren's. The simpler,
the better). Email address validation is error prone. Check:

http://aspn.activestate.com//ASPN/Reference/Products/ActivePerl/lib/Pod/perl
faq9.html#how%20do%20i%20check%20a%20valid%20mail%20address

Specifically, IP addresses can be given as 'number.number' or 'number' (i.e.
not just quadruple),
you forgot the '$' at the end, so sometimes there's only a partial match,
and, if I got it right, your pattern accepts digits in the host name only
(when you include the '$', of course).

I use the following code:

function isValidEmail(str) {
    if (!str.replace) {
        // broswer does not support REs
        return (str.indexOf("@") != -1);
    }
    else {
        var re = new
RegExp("^\\s*[\\w\\-\\.]+\\@[\\w\\-]+(\\.[\\w\\-]+)+\\s*$");
        return re.test(str);
    }
}

(I haven't included a ":port" part.)

It works on old browsers as well (it has "new RegExp", not an RE literal).

The following article has some more code.

http://tech.irt.org/articles/js049/index.htm






More information about the thelist mailing list