0

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?

3
  • 1
    Honestly, I'd tackle this with JS/jQuery instead that way you're giving the user immediate feedback if they're making a mistake rather than waiting for them to submit. gist.github.com/jessegilbride/19d4d18db9f06eb35bbe1d57129aa43e – Tony Djukic Jan 29 at 18:12
  • Holy crap - this is an example of using the wrong tool for the task. I can't believe I didn't even think about this route. Thank you – david lee Jan 29 at 19:18
  • You're welcome... ...sometimes you get working on something and you get deep into it and everything external to it ends up being beyond grasp. I had the exact same thing with Canadian Postal Codes and took a break to order something for my kid and the site validated my Postal Code immediately and I was like "Hey! Why am I not doing this instead?" Lol! – Tony Djukic Jan 29 at 19:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.