14 Feb

Simple WordPress Contact Form 7 Phone Validation

I looked around for a simple Contact Form 7 phone validation however all the solutions I found relied on hacking the Contact Form 7 code. By looking through the CF7 code I found a way to attach a simple function to the validation to allow custom validation of any input type you like

To plug into the Contact Form 7 validation there are some filters you can attach to. The built in validation functions do this so we’re copying the standard CF7 way of validation.

All of the code given here can be put into the functions.php file in your wordpress theme.


add_filter( 'wpcf7_validate_text', 'drc_wpcf7_validate_text' , 10, 2 );
add_filter( 'wpcf7_validate_text*', 'drc_wpcf7_validate_text' , 10, 2 );

This code attaches to two filter calls – one for a text field (wpcf7_validate_text) and one for a required text field (wpcf7_validate_text* – note the asterisk at the end).


function drc_wpcf7_validate_text( $result, $tag ) {
$type = $tag['type'];
$name = $tag['name'];
$value = $_POST[$name] ;

if ( strpos( $name , 'phone' ) !== false ){
$regex = '/^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$/';
$Valid = preg_match($regex,  $value, $matches );
if ( $Valid > 0 ) {
$formatted = "($matches[1]) $matches[2]-$matches[3]";
if ($matches[4]) $formatted .= " x$matches[4]";
// Replace the value passed in with the cleaned up version.
$_POST[$name] = $formatted ;
}
else {
$result['valid'] = false;
$result['reason'][$name] = 'Phone field invalid';
}
}

return $result;
}

This simple routine gets called to validate all text fields in your form. The strpos looks for a field name containing ‘phone’ i.e. ‘your-phonenumber’ and will validate that. This is very simple to extend to Zip codes or any other text field you would like validated. By setting $result[‘valid’] to false we tell Contact Form 7 that the validation failed, the value you set for $result[‘reason’][$name] is the message that is displayed to the user of the site.

9 thoughts on “Simple WordPress Contact Form 7 Phone Validation

  1. This looks great and I believe I understand how to implement it. Can you tell me though, what phone formats the code will validate and what will fail (like will all these work: xxxxxxxxxx, (xxx)xxx-xxxx, or xxx-xxx-xxxx)? Also, can you explain specifically how the code wood need to be changed to validate Zip codes or other text fields?

    • Validates xxx xxx xxxx
      also (xxx) xxx xxxx
      and xxx-xxx-xxxx
      and 1-xxx-xxx-xxxx
      Does not validate xxxxxxxxxx – you can add to the code to handle this situation.

      • Thanks, Dylan. I do appreciate that you are willing to share this. Like you, I couldn’t find any existing solutions that wouldn’t be obliterated every time the Contact Form 7 plugin gets updated. So this is really cool. However, it seems like you left out the most important validation as most folks would rather just enter the numbers. You seem to be encouraging me (and other readers?) to learn enough PHP to work out how to “add to the code” to include this check. Is that your intent or are you willing to provide more specifics and possibly update your code?

        • Good News, I think. I found a posting by Corey on php.net that lists the same regular expression you are using. This seems to indicate that the script validates when just numbers are entered (as well as a host of other combinations including extensions and whatnot). In my own testing of your script I found that just entering numbers worked! Here is the link:
          http://www.php.net/manual/en/function.preg-match.php#90503

  2. Would be nice if you could also explain what is being done in the regex expression. Otherwise it’s a well explained simple script.

    Cheerio,
    Mel

  3. Thanks for this code… It works great. I’ve implemented it for both phone numbers and zip codes. The only issue I am having is when I don’t want these fields to be “required”. Even though I’m leaving off the * (asterisk) when implementing the text inside of the “contact” tab in WordPress, it still requires the fields to be filled in. Has anyone tried this code as just “optional” input? I would like the fields to be validated when there is data to evaluate, but if they are left blank, I am simply looking for the fields to be ignored. Any thoughts?

    • You will need to trap the ‘*’ version and implement special handling for that. The built in Contact Form text validation code works like:
      if ( ‘text*’ == $type ) {
      if ( ” == $_POST[$name] ) {
      $result[‘valid’] = false;
      $result[‘reason’][$name] = wpcf7_get_message( ‘invalid_required’ );
      }
      }
      So you would need to change the code to look for the type being ‘text*’ and make it required and if type is ‘text’ then its not required. The current code in the post above makes the field required, you could change the code
      if ( $Valid > 0 ) { … success … } else { … error … }
      to
      if ( $Valid > 0 ) { … success … } elseif ( $type == ‘text’ && $value == ” ) { … empty field success … } else { … error … }

Leave a Reply

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