Home is for the experience. Projects are for the ones who are interested!

Custom Validatation For Phone Number Field Contact Form 7

Custom Validatation For Phone Number Field Contact Form 7

Even if contact form 7 comes with many validation rules for its fields, sometimes you need a custom validation rule for a certain fields. Today we will task as an example the phone number where we will add a custom regex function to check how many numbers the number has and if it start with a ceratin number.

As you will in the below function we will need to check all these things in php so our code will go to the functions.php file. First of all we have to get the on submit event of the contact form, there we will check the value of the phone number from the data which comes from POST message. If the number phone fields does not pass our rules we will return an error message to the form.

With the following function we add a filter for the tel input and force contact form to check our function too at the validation.

function custom_filter_wpcf7_is_tel( $result, $tel ) { 
  $result = preg_match( '/^(?:0)\d{9}+$/', $tel );
  return $result; 
}
add_filter( 'wpcf7_is_tel', 'custom_filter_wpcf7_is_tel', 10, 2 );

That's it, now when a user try to submit a phone number which does not pass this regex and error will be thrown. You can change the regex verification with your own.

Leave a Reply

Your email address will not be published. Required fields are marked *