I want to add custom validation for Email and tel fields. I’m having two fields Email and Phone, Initially two fields should be mandatory, if the user filled any one of the field and submits the form it should be submitted.
I’ve added this code but it is now working.
add_filter('wpcf7_validate', 'custom_cf7_validation', 20, 2);
function custom_cf7_validation($result, $tags)
{
// Get the values of the two fields
$field1_value = isset($_POST['your-email']) ? sanitize_email_field($_POST['your-email']) : '';
$field2_value = isset($_POST['your-phone']) ? sanitize_text_field($_POST['your-phone']) : '';
// If either field has a value, make the other field not required
if (!empty($field1_value) || !empty($field2_value)) {
$field1 = $tags[0];
$field2 = $tags[1];
$field1->set_properties(array('required' => false));
$field2->set_properties(array('required' => false));
}
return $result;
}
Above code showing the below error:
POST https://example.com/wp-json/contact-form-7/v1/contact-forms/524/feedback 500
Response {type: 'basic', url: 'https://example.com/wp-json/contact-form-7/v1/contact-forms/524/feedback', redirected: false, status: 500, ok: false, …}
2
Answers
There were some parts missing from CF7, so here is a code that should work:
Just make sure to replace
'your-email'
and'your-phone'
with the correct names of your email and phone fields in the CF7 form.This is actually quite complex to achieve in CF7 because the plugin isn’t designed for complex validation.
The reason why your approach fails is that the
wpcf7_validate
fires after CF7 has validated the submission and filled in the$result
object with the error msgs.Therefore, you need to rebuilt the
$result
object and return that instead. There is a plugin that will do this automatically for you, the Smart Grid-layout extension for CF7 allows you to validate fields based on other submissions, so the simplest way to achieve this with that plugin enabled is using the following hook,This is the simple solution.
Now, if you want to do it the hard way, this is what you need to do:
NOTE: haven’t tested the above code, but it gives you the basic idea of that is required.