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

    Custom validation example:

    you can only enter numbers that are a power of 2 in the fields below.

    Form Code

    <strong>Custom validation example:</strong><br>
    you can only enter numbers that are a power of 2 in the fields below.
    [repeater r]
        [text* powerof2]
    [/repeater]
    [submit "Send"]

    Email Body

    <strong>Entered values:</strong><br>
    <ul>[r]<li>[powerof2]</li>[/r]</ul>

    Edit this form in the form tester