javascript - Validate an email address -
how check user's email address ends in on of three
@camel.com, @mel.com, @camelofegypt.com
this code far, validates whether or not user has provided text
if ($.trim($("#email").val()).length === 0) { alert('you must provide valid input'); return false;
i want implement email address validation code.
as described in library regular expressions, difficult validate email address. however, below taken above website job.
the official standard known rfc 2822. describes syntax valid email addresses must adhere to. can (but shouldn't--read on) implement regular expression:
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
simple regex:
\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}\b
trade offs of validating email addresses:
yes, there whole bunch of email addresses pet regex doesn't match. quoted example addresses on .museum top level domain, longer 4 letters regex allows top level domain. accept trade-off because number of people using .museum email addresses extremely low. i've never had complaint order forms or newsletter subscription forms on jgsoft websites refused .museum address (which would, since use above regex validate email address).
however, if want specific domain possibility not recommended deny email address because fails these regular expressions.
taking above validate using following regex:
\b[a-z0-9._%+-]+@(camel|mel|camelofegypt)\.com\b
or:
^[a-z0-9._%+-]+@(camel|mel|camelofegypt)\.com$
the difference between these 2 regex simple, first regex match email address contained within longer string. while second regular expression match if whole string email address.
javascript regex:
/\b[a-z0-9._%+-]+@(camel|mel|camelofegypt)\.com\b/i
or:
/^[a-z0-9._%+-]+@(camel|mel|camelofegypt)\.com$/i
special note: should allow case insensitive regex using i
parameter since john@camel.com
same john@camel.com
. i've done in above regex.
Comments
Post a Comment