Thursday, June 14, 2007

Email validation review

A few days ago I posted a super simple function to validate email. Upon review, i realised that it didn't take into account .info or if they have @ipaddress.
Both of these are quite valid, but would be denied by that function.
Here is what I use instead:
function is_email_valid($email) {
if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
return false;
}
$email_array = explode("@", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
return false;
}
}
if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) {
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false;
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
return false;
}
}
}
return true;
}

Sorry about the formatting for the longer lines doing the regular expressions, but you get the drift?

BFN

No comments: