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.

0 0 votes
Article Rating
Notify of
1 Comment
Newest Most Voted
Inline Feedbacks
View all comments
3 years ago

Hi! Can you plz share phone number validation with country code using regex? l

Would love your thoughts, please comment.x