• Can I override error messages for required fields that are left blank via a hook?

    ## What I tried

    I tried to change the error message for an empty required checkbox in my form to something different from the text field.
    For example, something like “Please select at least one option.”

    I wrote the following code in functions.php, but no change occurred.

    add_filter('wpcf7_validate_checkbox*', 'custom_checkbox_validation', 99, 2);
    
    function custom_checkbox_validation($result, $tag)
    {
        if ($tag->name == 'my-checkbox') {
            $value = isset($_POST[$tag->name]) ? $_POST[$tag->name] : array();
    
            if (empty($value)) {
                $result->invalidate($tag, "Please select at least one option.");
            }
        }
        return $result;
    }

    When I commented out the following line in this plugin as a test, only the checkbox error message displayed as intended.
    (Of course, all other error messages are no longer displayed.)

    https://github.com/rocklobster-in/contact-form-7/blob/3c3342948d20d606a9135e5fb8517c94a05e80b4/includes/swv/schema-holder.php#L39-L41

    I suspect this line is overriding wpcf7_validate_checkbox*.

    Thanks for taking the time to read this!

    Contact Form 7 : v6.1.1
    WordPress : v6.8.2

Viewing 2 replies - 1 through 2 (of 2 total)
  • Plugin Author Takayuki Miyoshi

    (@takayukister)

    An attempt to invalidate a field (WPCF7_Validation::invalidate()) will be ignored if the field already has a validation error.

    Thread Starter Miral Kashiwagi

    (@miralkashiwagi)

    Thank you for your reply!

    So it seems there’s no way to use a hook to change the error message for an empty required checkbox to something different from the error message for an empty required text field.

    If anyone knows of another good way to make the messages different for each field type, I’d be grateful if you could let me know!

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘Error messages cannot be customized for each field type’ is closed to new replies.