Skip to content

Instantly share code, notes, and snippets.

@evandonovan
Created May 13, 2010 03:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evandonovan/399477 to your computer and use it in GitHub Desktop.
Save evandonovan/399477 to your computer and use it in GitHub Desktop.
code to validate email addresses (via MX address & PHP mail well-formedness rules)
/**
* Implements hook_user().
* Does advanced email validation.
*/
function revolven_user($op, &$edit, &$account, $category = NULL) {
if($op == "validate") {
if($error = adv_email_validate($edit['mail'])) {
form_set_error('mail', $error);
}
}
}
// Sets error for invalid emails
function adv_email_validate($mail) {
$valid_email = wellformed_email_address($mail);
if($valid_email == FALSE) { return t('The e-mail address %mail is not valid.', array('%mail' => $mail));
}
}
/** Checks if an email address is well-formed
* and MX record is present.
* Requires PHP 5.2 and checkdnsrr() function.
*/
function wellformed_email_address($mail) {
// simply return TRUE if PHP version is too low
$version = version_compare(phpversion(), "5.2");
if($version < 0) {
return TRUE;
}
// also return TRUE if checkdnsrr does not exist
if(!function_exists("checkdnsrr")) {
return TRUE;
}
if(filter_var($mail, FILTER_VALIDATE_EMAIL)) {
$form_valid = TRUE;
}
else {
$form_valid = FALSE;
}
list($username, $maildomain) = split("@", $mail);
if(checkdnsrr($maildomain, "MX")) {
$domain_valid = TRUE;
}
else {
return FALSE;
}
if($form_valid && $domain_valid) {
return TRUE;
}
else {
return FALSE;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment