Custom validation to validate phone number for Country & Phone Field Contact Form 7 WP Plugin

I am a Country & Phone Field Contact Form 7 plugin developer. Recently one of the subscribers asked to validate the phone number.

Subscriber Query

Is it possible to exclude inputs like 55555555 or 9999999 ? This would help us a lot to get more valid phone numbers through our contact form.

Solutions code snippet

add_filter( 'wpcf7_validate_phonetext', 'prefix_phonetext_validation_filter', 10, 2 );
add_filter( 'wpcf7_validate_phonetext*', 'prefix_phonetext_validation_filter', 10, 2 );

function prefix_phonetext_validation_filter( $result, $tag  ){

	$type = $tag->type;
	$name = $tag->name;
	$extension = $_POST[$name.'-country-code'];

	$value = isset( $_POST[$name] ) ? (string) wp_unslash($_POST[$name]) : '';
	$value = str_replace($extension , '', str_replace(" ", "" , $value));
	$str_array = str_split($value);
	//print_r($str_array); die;
	if ( '' != $value && count(array_unique($str_array)) === 1 ) {
		$result->invalidate( $tag, __('Phone number must be correct. Not same number repeat', 'nb-cpf') );
	}

	return $result;
}

How to implement

  • Copy above code snippet.
  • Paste this code into your currently active theme functions.php file
  • I recommend using a child theme, so this code will not remove from theme if in the future you update your third party free/paid theme
  • You can update the validation message. If you want.

I hope, it will work for you.
Happy blogging 🙂