phpvalidationcontact-form-7

Custom error message for Contact Form 7 - Can check everything but if it's empty


I'm seem to be going crazy over here :)

I'm using the following code to check if a contact form 7 field with the name "your-name" if empty, and if so , display a custom error message.

I've tried both checking for an empty string >

add_filter('wpcf7_validate_text*', 'custom_text_validation_filter', 20, 2);

function custom_text_validation_filter($result, $tag) {
    
    if ('your-name' == $tag->name) {
        $field_name = isset( $_POST['your-name'] ) ? trim( $_POST['your-name'] ) : '';
        
        if ($field_name == '') {
             $result->invalidate( $tag, "Are you sure this is the correct name?" );
        }
    }

    return $result;
}

add_filter('wpcf7_validate_text*', 'custom_text_validation_filter', 20, 2);

And checking using PHP's empty function

add_filter('wpcf7_validate_text*', 'custom_text_validation_filter', 20, 2);

function custom_text_validation_filter($result, $tag) {
    
    $tag = new WPCF7_FormTag($tag);
    
    if ('your-name' == $tag->name) {
        $field_name = isset( $_POST['your-name'] ) ? trim( $_POST['your-name'] ) : '';
        
        if (empty($field_name)) {
             $result->invalidate( $tag, "Are you sure this is the correct name?" );
        }
    }

    return $result;
}

Neither of these work.

Here is the crazy part. I CAN check for anything else BUT being empty. For example I can check if it is NOT empty using >

if ($field_name !== '') {
    $result->invalidate( $tag, "Why did you type something?" );
}

And that works fine if i try to submit the form with anything in the name field.

showing working example if checking if not empty

I can also check if it contains a certain character like >

if ($field_name == 'abcd') {
    $result->invalidate( $tag, "efg?" );
}

And that also works perfect.

showing checking for characters working

BUT if i check if the field is empty, it returns the default error message.

if ($field_name == '') {
    $result->invalidate( $tag, "I think you meant for something to be here?" );
}

showing checking if empty not working

Does anyone know why checking if it's empty may not be working?


Solution

  • If any one else runs into this, CBroe nailed it. The reason why it wasn't working is because when you add the asterisk (*) to the field, it uses CF7's validation and pretty much renders yours useless (Unless your able to find the hook for it).

    The answer was simple, which was to make the field NOT required (Not using Cf7's logic).

    Then when you use the snippet I posted, it will use YOUR validation and you can do whatever you want in it.

    Change this >

    [text* your-name]

    To >

    [text your-name] and your good to go to add your custom validation in!