Last active
September 20, 2020 03:24
-
-
Save webdevsuperfast/aa7f33a5f302aa18a37e9fb1419b4865 to your computer and use it in GitHub Desktop.
Validate US Phone Number Format in Contact Form 7
This file contains 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 | |
// Validate Phone Numbers for US | |
function validate_phone( $phone ) { | |
return preg_match( "/^\(?([0-9]{3})\)?[-.●]?([0-9]{3})[-.●]?([0-9]{4})$/i", $phone ); // @link https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch04s02.html | |
} | |
add_filter( 'wpcf7_validate_tel', 'tc_validate_tel', 20, 2 ); | |
add_filter( 'wpcf7_validate_tel*', 'tc_validate_tel', 20, 2 ); | |
function tc_validate_tel( $result, $tag ) { | |
$type = $tag['type']; | |
$name = $tag['name']; | |
$value = $_POST[$name]; | |
if( validate_phone( $value ) ) : | |
else : | |
$result->invalidate( $tag, wpcf7_get_message( 'invalid_us_phone' ) ); | |
endif; | |
return $result; | |
} | |
add_filter( 'wpcf7_messages', function( $messages ) { | |
return array_merge( $messages, array( | |
'invalid_us_phone' => array( | |
'default' => __( 'Invalid US Phone format, use the XXX-XXX-XXXX format.' ) | |
), | |
) ); | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment