Created
November 5, 2014 08:08
-
-
Save HarishChaudhari/405ed2c5e78e6b2375d8 to your computer and use it in GitHub Desktop.
Contact Form 7 custom validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Add custom validation for CF7 form fields | |
function custom_text_validation_filter($result,$tag){ | |
$type = $tag['type']; | |
$name = $tag['name']; | |
$the_value = $_POST[$name]; | |
if($name == 'firstname'){ | |
if( empty($the_value) ) { | |
$result['valid'] = false; | |
$result['reason'][$name] = 'Please fill the required field.'; | |
} else { | |
if( !preg_match( '/^([a-zA-Z \-.\'.\_]+)$/', stripslashes(str_replace( "'", "", $the_value))) ){ | |
$result['valid'] = false; | |
$result['reason'][$name] = 'Please enter valid first name.'; | |
} | |
} | |
} | |
if($name == 'lastname'){ | |
if( empty($the_value) ) { | |
$result['valid'] = false; | |
$result['reason'][$name] = 'Please fill the required field.'; | |
} else { | |
if( !preg_match( '/^([a-zA-Z \-.\'.\_]+)$/', stripslashes(str_replace( "'", "", $the_value))) ){ | |
$result['valid'] = false; | |
$result['reason'][$name] = 'Please enter valid last name.'; | |
} | |
} | |
} | |
if($name == 'city'){ | |
if( !empty($the_value) ) { | |
if( !preg_match( '/^([a-zA-Z \-.\'.\_]+)$/', stripslashes(str_replace( "'", "", $the_value))) ){ | |
$result['valid'] = false; | |
$result['reason'][$name] = 'Please enter valid city name.'; | |
} | |
} | |
} | |
if($name == 'phone'){ | |
if( !empty($the_value) ) { | |
if( !preg_match( '/^(?:\([0-9]\d{2}\)\ ?|(?:[0-9]\d{2}\-))[0-9]\d{2}\-\d{4}$/', $the_value ) ){ | |
$result['valid'] = false; | |
$result['reason'][$name] = 'Please enter valid phone no.'; | |
} | |
} | |
} | |
return $result; | |
} | |
add_filter('wpcf7_validate_text','custom_text_validation_filter', 10, 2); // Normal field | |
add_filter('wpcf7_validate_text*', 'custom_text_validation_filter', 10, 2); // Req. field | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment