Contact Form 7: Add a custom verification/validation filter

The following PHP code is fully working when placed in the theme’s functions.php file or in a plugin. This checks the email address provided against a list of free email providers to better ensure that the only submissions you receive are using a company email address. It’s isolated to only be applied to email fields with the form field name of “company-email”.

That said, this can be easily modified to do whatever validation needs to be done. Just change out the function that returns true/false based on a condition, change the form field name it’s looking for, swap out the fail message, and change the form field that it’s applied to.

// Add custom validation for CF7 form fields
function is_company_email($email){ // Check against list of common public email providers & return true if the email provided doesn't match one of them
if(
preg_match('/@gmail.com/i', $email) ||
preg_match('/@hotmail.com/i', $email) ||
preg_match('/@live.com/i', $email) ||
preg_match('/@msn.com/i', $email) ||
preg_match('/@aol.com/i', $email) ||
preg_match('/@yahoo.com/i', $email) ||
preg_match('/@inbox.com/i', $email) ||
preg_match('/@gmx.com/i', $email) ||
preg_match('/@me.com/i', $email)
){
return false; // It's a publicly available email address
}else{
return true; // It's probably a company email address
}
}
function custom_email_validation_filter($result,$tag){
$type = $tag['type'];
$name = $tag['name'];
if($name == 'company-email'){ // Only apply to fields with the form field name of "comany-email"
$the_value = $_POST[$name];
if(!is_company_email($the_value)){ // Isn't a company email address (it matched the list of free email providers)
$result['valid'] = false;
$result['reason'][$name] = 'You need to provide an email address that isn\'t hosted by a free provider.
Please contact us directly if this isn\'t possible.';
}
}
return $result;
}
add_filter('wpcf7_validate_email','custom_email_validation_filter', 10, 2); // Email field
add_filter('wpcf7_validate_email*', 'custom_email_validation_filter', 10, 2); // Req. Email field

Also, I hope the developer of Contact Form 7 knows how great he is for making this sort of thing possible.