Snippet: Phone and Fax Number Validation in Contact Form 7

Contact Form 7 is the most simple and straight forward form plugin for WordPress. It has been downloaded nearly 10 million times. It has everything to set up a simple contact form except one thing, that is, validation of a phone or fax number. This short snippet validates phone number by stripping of all non-numeric characters and checking if numeric string is of length 10 digits.

Snippet

function wpds_validate_phone_number($result, $tag) {
    $field_name = $tag['name'];
    if ($field_name == 'your-phone') { // Specify the field name of your telephone.
        $tel = preg_replace('/\D/', '', $_POST[$field_name]);
        if (strlen($tel) != 10) { // Check length of the string. It must be of length 10
            $result['valid'] = false;
            $result['reason'][$field_name] = 'Please enter valid 10 digit phone number. ex. 123-456-7890';
        }
    }
    return $result;
}
add_filter('wpcf7_validate_text', 'wpds_validate_phone_number', 10, 2);
add_filter('wpcf7_validate_text*', 'wpds_validate_phone_number', 10, 2);

2 Responses to Snippet: Phone and Fax Number Validation in Contact Form 7

  1. parth says:

    sir where to add this code?

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>