Repeater: custom validation

Contact Form 7 allows developers to create custom validation rules using the wpcf7_validate_ + {type of the form-tag} filter hook.

This works perfectly fine if you are using conditional fields as well, but needs a small tweak when you are using the repeater function of Conditional Fields PRO.

The fields in a repeater will be submitted with a suffix, __1, __2, etc.

So in order to validate these fields, you need to only get the part before the suffix. One way to achieve this is like this:

explode('__',$tag->name)[0] === 'your-field'

This condition will match your-field__1, your-field__2, etc.

Full example

The below examples requires you to add this code to your theme’s functions.php file:

add_filter( 'wpcf7_validate_text', function($result, $tag) {
    if (explode('__',$tag->name)[0] === 'powerof2') {
        $value = $_POST[$tag->name];
        if (!is_power_of_2($value)) {
            $result->invalidate($tag, 'The value should be a power of 2, like for example 4, 8, 16, 32, ...');
        }
    }
    return $result;
}, 10, 2);

function is_power_of_2($n) {
    return ($n & ($n - 1)) == 0;
}

Form

Error: Contact form not found.

Form Code

Error: Contact form not found.

Email Body

Error: Contact form not found.

Edit this form in the form tester