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, …}
There were some parts missing from CF7, so here is a code that should work:
add_filter('wpcf7_posted_data', 'custom_cf7_validation');
function custom_cf7_validation($posted_data)
{
$email_value = isset($posted_data['your-email']) ? sanitize_email($posted_data['your-email']) : '';
$phone_value = isset($posted_data['your-phone']) ? sanitize_text_field($posted_data['your-phone']) : '';
// If either email or phone has a value, remove the other from the required validation
if (!empty($email_value) || !empty($phone_value)) {
if (!empty($email_value)) {
unset($posted_data['your-phone']);
} else {
unset($posted_data['your-email']);
}
}
return $posted_data;
}
Just make sure to replace 'your-email'
and 'your-phone'
with the correct names of your email and phone fields in the CF7 form.