I have an address form generated via Contact7. I need to validate there is a 5 digit zip code.
According to the docs, I came up with this function and placed it in my functions.php file
add_filter( 'wpcf7_validate_text*', 'custom_zip_validation_filter', 20, 2 );
function custom_zip_validation_filter( $result, $tag ) {
if ( 'zip' == $tag->name ) {
$zip = isset( $_POST['zip'] ) ? trim( $_POST['zip'] ) : '';
$result = '/^([0-9]{5})?$/i';
if (!preg_match($result, $zip, $matches)) {
$result->invalidate($tag, "Please enter a valid zip code" );
}
}
return $result;
}
Then in my Contact7 form, I put this line for the zip code [text* zip class:zip id:zip placeholder "ZIP"]
However, when I go to the form and input the ZIP code, I am able to submit a ZIP code of less than 5 digits or greater than 5 digits.
How can I get the error message "Please enter a valid zip code?" to appear when a user inputs a ZIP code != 5 digits?