I have two text fields on my contact form: Cost Plus and Flat Rate.
I need one of the two to be required. If cost-plus not entered, flat-rate is required.. and vice verse. This code in functions.php, doesn’t seem to be giving me any feedback.
add_filter( 'wpcf7_validate_text', 'custom_form_validation_filter', 20, 2 );
function custom_form_validation_filter( $result, $tag ) {
$tag = new WPCF7_FormTag($tag);
if ('cost-plus' == $tag->name) {
$cost_plus = isset($_POST['cost-plus']) ? trim($_POST['cost-plus']) : '';
$flat_rate = isset($_POST['flate-rate']) ? trim($_POST['flate-rate']) : '';
if ( empty($cost_plus) && empty($flat_rate) ) {
$result->invalidate( $tag, "You must enter a Cost Plus OR Flat Rate value." );
}
}
return $result;
}
2
Answers
The code below should work for your use-case. Perhaps you will need some extra checks dependent on what values are sent in the post request from the front-end. If the code below does not work for your use-case, please consider posting the entire POST request here for debugging purposes.
Don’t know if I’m late but I managed to achieve this using ‘wpcf7_validate’ hook, looping through the tags in the form and checking if both of them are empty, and i f they are I invalidate them like this:
Might need some improvement.