How to Show Custom Error message in Contact form 7

Sometimes we need to add a custom form with the contact form 7 plugin, where we need to customize error messages based on the user input value, like if you created a form for a mortgage application, where you need to validate a few inputs and file based on user/client input, we can do it two way, by the plugin. where have a few limitations? and by adding a filter.

For example, if you want to confirm email by adding another email confirm input, and if email input is not matched, we can show this “Are you sure this is the correct address?”

add_filter( 'wpcf7_validate_email*', 'custom_email_confirmation_validation_filter', 20, 2 );

function custom_email_confirmation_validation_filter( $result, $tag ) {
if ( 'your-email-confirm' == $tag->name ) {
    $your_email = isset( $_POST['your-email'] ) ? trim( $_POST['your-email'] ) : '';
    $your_email_confirm = isset( $_POST['your-email-confirm'] ) ? trim( $_POST['your-email-confirm'] ) : '';

    if ( $your_email != $your_email_confirm ) {
        $result->invalidate( $tag, "Are you sure this is the correct address?" );
    }
}

return $result;
}

You have to input the field name in add_filter first argument, Like wpcf7_validate_text, you have add ‘*’, if field is required. like wpcf7_validate_text*. as an example, if you want to check the text field:

 add_filter( 'wpcf7_validate_text*', 'custom_text_fname_validation_filter', 20, 2 );
function custom_text_fname_validation_filter( $result, $tag ) {
if ( 'first-name' == $tag->name ) {
    $firstname = isset( $_POST['first-name'] ) ? trim( $_POST['first-name'] ) : '';
    if ( !empty($firstname) ) {
        $result->invalidate( $tag, "Your First name is required." );
    }
}

return $result;
}

You can check more details at Contact form 7 custom validation. if you have any issues, just let me know in the comment section below. we will discuss it solve it.

Add a Comment