Search code examples
phpformsvalidationcontact-form-7

Contact Form 7 custom validation for specific form id


I'm using custom validation in Contact Form 7, but I need to validate only for a specific form, not for all my forms. This is my code:

add_filter( 'wpcf7_validate_text*', 'my_custom_text_validation_filter', 20, 2 );
function my_custom_text_validation_filter( $result, $tag ) {

    $tag = new WPCF7_Shortcode( $tag );

    if ( 'name' == $tag->name ) { // validate name field only

        .... // my validation here

    }

    return $result;
}

Solution

  • CF7 always adds to the form a hidden field named _wpcf7, containing the form id. It's possible to use that field in order to check what form you are validating before executing your code:

    add_filter( 'wpcf7_validate_text*', 'my_custom_text_validation_filter', 20, 2 );
    function my_custom_text_validation_filter( $result, $tag ) {
    
        if ( isset($_POST['_wpcf7']) && $_POST['_wpcf7'] != 166) // Only form id 166 will be validated.
            return $result;
    
        $tag = new WPCF7_Shortcode( $tag );
    
        if ( 'name' == $tag->name ) { // validate name field only
    
            .... // my validation here
    
        }
    
        return $result;
    }