↑
Main Page
Validating e-mail addresses
Validating e-mail addresses
Creating a pattern to match all valid e-mail addresses is quite an undertaking. The specification that
defines what a valid e-mail address is, RFC 2822, defines all the following patterns as valid:
?
john@somewhere.com
?
john.doe@somewhere.com
?
John Doe <john.doe@somewhere.com>
?
“john.doe”@somewhere.com
?
john@[10.1.3.1]
Realistically, however, you will probably only see the first three variations and only the first two would
ever be entered by a user into a text box on your Web site (or Web application). For this reason, this sec-
tion focuses on validating these two patterns.
You already know the basic format for an e-mail address is a bunch of characters (which can be num-
bers, letters, dashes, dots — pretty much anything but spaces), followed by an
at
(@) symbol, followed by
more characters. You also know (perhaps only subconsciously), that at least one character must precede
the @ and at least three must come after it, the second of which must be a period (a@a.b is a valid e-mail
address, a@a and a@a. are not).
The text before and after the @ follows the same two rules: It cannot begin or end with a period, and it
cannot have two periods in a row. Therefore, the regular expression is the following:
var reEmail = /^(?:\w+\.?)*\w+@(?:\w+\.?)*\w+$/;
The expression begins with a non-capturing group
(?:\w+\.?)
, which tells you that any number of
word characters can be followed by zero or one periods. This can happen zero or more times (such as
a.b.c.d
), so the asterisk is used for that group.
The next part of the expression is
\w+@
, which ensures that a word character is always before the @.
Immediately after that is the same non-capturing group,
(?:\w+\.?)
, which can also appear zero or
more times, so the asterisk is used. The last part of the regular expression is
\w+$
, which states that a
word character must be the last character on the line, disallowing e-mail addresses such as “john@doe.”.
Just wrap this pattern in a function and you’re ready to go:
function isValidEmail(sText) {
var reEmail = /^(?:\w+\.?)*\w+@(?:\w+\.?)*\w+$/;
return reEmail.test(sText);
}
This function can be called like so:
alert(“john.doe@somewhere.com”); //outputs “true”
alert(“john.doe@somewhere.”); //outputs “false”
222
Chapter 7
10_579088 ch07.qxd 3/28/05 11:38 AM Page 222
Free JavaScript Editor
Ajax Editor
©
→