Am using Contact Form 7 latest version (5.6.3) on our site and when we try to add custom validation using hooks, it doesn’t work for empty field validation. The hooks work fine when we roll back the plugin version to 5.5.6.1.
Here am attaching the screenshot of the forms. this is a screenshot for version 5.6.3 https://snipboard.io/cSusk3.jpg and this is for version 5.5.6.1 https://snipboard.io/obIpS9.jpg.
Please Check the empty field value error message. Please add this code to your site and check it. The difference between the latest version and version 5.5.6.1 can be seen then.
add_filter('wpcf7_validate_text', 'custom_text_validation', 1, 2); add_filter('wpcf7_validate_text*', 'custom_text_validation', 1, 2); function custom_text_validation($result, $tag) { $type = $tag->type; $name = $tag->name; if($name == 'Name') { $value = $_POST['Name']; if($value==''){ $result->invalidate($tag, "Please enter your name."); } } return $result; }
Advertisement
Answer
To me, it’s confusing as to why your general function didn’t work. I’ve written other $result->invalidate
functions, and they all work, but testing yours did not. This is what I came up with, but what happens is that if there’s other text
field errors their error message won’t show until the Please enter your name
message is cleared. This to me doesn’t seem like a big problem.
add_filter( 'wpcf7_validate_text', 'custom_text_validation', 10, 2 ); add_filter( 'wpcf7_validate_text*', 'custom_text_validation', 10, 2 ); function custom_text_validation( $result, $tag ) { if ( 'Name' === $tag->name && empty( $_POST['Name'] ) ) { $result = new WPCF7_Validation(); $result->invalidate( $tag, __( 'Please enter your name.' ) ); } return $result; }