I looked around for a simple Contact Form 7 phone validation however all the solutions I found relied on hacking the Contact Form 7 code. By looking through the CF7 code I found a way to attach a simple function to the validation to allow custom validation of any input type you like

To plug into the COontact Form 7 validation there are some filters you can attach to. The built in validation functions do this so we’re copying the standard CF7 way of validation.

All of the code given here can be put into the functions.php file in your wordpress theme.


add_filter( 'wpcf7_validate_text', 'drc_wpcf7_validate_text' , 10, 2 );
add_filter( 'wpcf7_validate_text*', 'drc_wpcf7_validate_text' , 10, 2 );

This code attaches to two filter calls – one for a text field (wpcf7_validate_text) and one for a required text field (wpcf7_validate_text* – note the asterisk at the end).


function drc_wpcf7_validate_text( $result, $tag ) {
$type = $tag['type'];
$name = $tag['name'];
$value = $_POST[$name] ;

if ( strpos( $name , 'phone' ) !== false ){
$regex = '/^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$/';
$Valid = preg_match($regex,  $value, $matches );
if ( $Valid > 0 ) {
$formatted = "($matches[1]) $matches[2]-$matches[3]";
if ($matches[4]) $formatted .= " x$matches[4]";
// Replace the value passed in with the cleaned up version.
$_POST[$name] = $formatted ;
}
else {
$result['valid'] = false;
$result['reason'][$name] = 'Phone field invalid';
}
}

return $result;
}

This simple routine gets called to validate all text fields in your form. The strpos looks for a field name containing ‘phone’ i.e. ‘your-phonenumber’ and will validate that. This is very simple to extend to Zip codes or any other text field you would like validated. By setting $result['valid'] to false we tell Contact Form 7 that the validation failed, the value you set for $result['reason'][$name] is the message that is displayed to the user of the site.

Post from: Top SEO Tips

Simple WordPress Contact Form 7 Phone Validation

No related posts.

Top SEM Tips