Skip to content

Instantly share code, notes, and snippets.

@webdevsuperfast
Last active September 20, 2020 03:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webdevsuperfast/aa7f33a5f302aa18a37e9fb1419b4865 to your computer and use it in GitHub Desktop.
Save webdevsuperfast/aa7f33a5f302aa18a37e9fb1419b4865 to your computer and use it in GitHub Desktop.
Validate US Phone Number Format in Contact Form 7
<?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