Search code examples
regexwordpresscontact-form-7

How to validate contact form 7 field from functions.php file in WordPress


I have a number field in contact form 7. It must be 11 digit number and first two digit must be 24 or 42. Please tell me how can i do this from functions.php file. This is my regular expression ^(24|42)\d{9}$ . But i can't use it on functions.php file


Solution

  • Check http://contactform7.com/2015/03/28/custom-validation/ for general information on form validation. Assuming your field has the type="number" and a name="eleven-digits" your filter could look like:

    add_filter( 'wpcf7_validate_number', function( $result, $tag ) {
        $tag = new WPCF7_Shortcode( $tag );
        if ( $tag->name = 'eleven-digits' && preg_match( '^(24|42)\d{9}$', $result ) ) {
            return true;
        }
    
        return false;
    } );
    

    If you want a more detailed answer, you should add more detail in your question.