Replace default validation error message with individual messages
-
Hi there, thanks for this awesome plugin!
I would like to replace the default “This field is required.” validation error message with individual messages determined by the specific field. So, for example
the field “your-name” returns the error “Please enter your name.“,
the field “your-email” returns “Please enter your e-mail.“
and the field “your-message” returns “Let us know, how we can help you.“Therefore, I wrote this code:
add_filter('wpcf7_validate_text*', 'custom_cf7_validation_filter', 20, 2); add_filter('wpcf7_validate_email*', 'custom_cf7_validation_filter', 20, 2); add_filter('wpcf7_validate_textarea*', 'custom_cf7_validation_filter', 20, 2); function custom_cf7_validation_filter($result, $tag) { $name = $tag->name; switch ($name) { case 'your-name': if (empty($_POST['your-name'])) { $result->invalidate($tag, "Please enter your name."); } break; case 'your-email': if (empty($_POST['your-email'])) { $result->invalidate($tag, "Please enter your e-mail."); } break; case 'your-message': if (empty($_POST['your-message'])) { $result->invalidate($tag, "Let us know, how we can help you."); } break; } return $result; }
The code works, but only if no other default error message is returned. Therefore I would need to disable the default “This field is required.” message or have a way to override it. Is this possible? Thanks in advance.
EDIT: To make the problem visible on the provided URL, I added a Test-Field with an always returning error message “Test error: This error is always displayed.” Code:
case 'test-feld-zum-testen': $result->invalidate($tag, "Test error: This error is always displayed."); break;
If you leave every field blank and click send, the “This field is required.” error gets displayed. If you now enter something in the test field, the “alwas displayed” error message gets displayed.
The page I need help with: [log in to see the link]
- The topic ‘Replace default validation error message with individual messages’ is closed to new replies.