Contact form 7 telephone number verification

Kiran Dash picture Kiran Dash · Feb 16, 2016 · Viewed 58.7k times · Source

I am trying to use the built in verification method for contact form 7 to verify a telephone number.

Contact form 7 markup:

<p>[number* your-telephone min:1000000000 max:9999999999 placeholder "Telephone number"] </p>

<p>[submit "submit"]</p>

So, what I am trying to do here is restrict phone number using the min and max properties of input type of number. But the problem here is that if I enter a telephone number say: 0402356584 then it is less than the min value but is still a phone number.

So, how can I set the min and max value to support all possible 10 digit telephone numbers?

Any other solution different from my approach is also most welcome. Because I have got a feeling that the verification can not be done using min and max attributes.

I also tried to edit the plugin files via functions.php file by using the code from a source but that did not work.

So, if any one has the perfect solution to validate telephone numbers on contact form 7 then please post your answers.

Answer

shishir mishra picture shishir mishra · Feb 13, 2017

You can use [tel* tel-672] field and validate according to your requirement through wpcf7_is_tel filter hook .

Contact form 7 has many pre-defined hooks through which you can validate any field.Here, in the Contact Form 7 formatting.php module, validation rule is defined by following method .You can override it by filter hook mentioned in apply_filters through functions.php

function wpcf7_is_tel( $tel ) {
    $result = preg_match( '/^[+]?[0-9() -]*$/', $tel );
    return apply_filters( 'wpcf7_is_tel', $result, $tel );
}

Please add the below mentioned code in functions.php in your activated theme folder and add your validation rule to $result

// define the wpcf7_is_tel callback 
function custom_filter_wpcf7_is_tel( $result, $tel ) { 
  $result = preg_match( '/^\(?\+?([0-9]{1,4})?\)?[-\. ]?(\d{10})$/', $tel );
  return $result; 
}

add_filter( 'wpcf7_is_tel', 'custom_filter_wpcf7_is_tel', 10, 2 );

You can see more