jenhuls
9/22/2014 - 7:54 PM

Validate text field as phone number in Contact Form 7 plugin. From http://blogs.lizardwebs.net/website-developer/a-solution-for-contact-for

Validate text field as phone number in Contact Form 7 plugin.

From http://blogs.lizardwebs.net/website-developer/a-solution-for-contact-form-7-phone-field/

<?php 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';
	}
    }
}