How to validate a field in CF7

What we need:

  • a filter 'wpcf7_validate_{$field_type}', which will filter the fields by type;
  • a function, which takes 2 arguments from Contact Form 7:
    • $result, which can be validated or invalidated before it is returned;
    • $tag, which helps us to identify the field by its name.

The {$field_type} is the exact field type that you have defined in your form, for example: text, text*, textarea, textarea*, email, etc.... The asterisk is used to indicate a required field, and yes, it has to be specified in the hook ( text is different from text* ).

Example

// hook our function:
add_filter( 'wpcf7_validate_text*', 'validate_phone', 20, 2 );

// define the function:
function validate_phone( $result, $tag ){

    // check if this is our phone field, and return the $result unchanged if it isn't:
    $tag = new WPCF7_Shortcode( $tag );
    if ( $tag->name !== 'phone' ){ return $result; }

    // if we got this far, then this is our phone input - we check to see if it is valid
    // assuming we have a function somewhere named "is_valid_phone"
    if( ! is_valid_phone('phone') ){
        $result->invalidate( $tag, 'This phone number is not valid! Please try again.' );
    }

    // finally, return the result:
    return $result;
}