Need to limit the size Zip Code fields in checkout page

This topic is empty.

Viewing 2 reply threads
  • Author
    Posts
    • #2944


      Bob Byers
      Guest

      U.S. Zipcodes can be either 5 digits (base) or 9 digits (extended). In Woocommerce a U.S. Zip code entry (either billing or shipping) that is not 5 digits in length will cause a tax error. I want to prevent users from entering anything than 5 numeric digits into the billing and shipping Zip fields. We ship only within the continental U.S. so handling other zip formats other than 5 numeric characters is not a concern. I’m told this has to be done in functions.php which I am not qualified to do. Can you help?

    • #2945


      Spiracle Themes
      Guest

      Hi Bob

      Thanks for reaching out
      Use a plugin called Code Snippets

      Code Snippets

      And add this code after creating a new snippet

      function soma_validate_us_zip() {
      $billing_zip = isset( $_POST[‘billing_postcode’] ) ? $_POST[‘billing_postcode’] : ”;
      $shipping_zip = isset( $_POST[‘shipping_postcode’] ) ? $_POST[‘shipping_postcode’] : ”;

      $regex = ‘/^\d{5}$/’;

      if ( ! preg_match( $regex, $billing_zip ) ) {
      wc_add_notice( ‘Please enter a valid 5 digit billing Zip code’, ‘error’ );
      }

      if ( ! preg_match( $regex, $shipping_zip ) ) {
      wc_add_notice( ‘Please enter a valid 5 digit shipping Zip code’, ‘error’ );
      }
      }
      add_action( ‘woocommerce_checkout_process’, ‘soma_validate_us_zip’ );

      Let us know if this works

      Best Regards

    • #2953


      Bob Byers
      Guest
      This reply has been marked as private.
      • #2954


        Spiracle Themes
        Guest

        Hi Bob

        You need to change the single quote to ‘

        Updated code

        function soma_validate_us_zip() {
        $billing_zip = isset( $_POST['billing_postcode'] ) ? $_POST['billing_postcode'] : ";
        $shipping_zip = isset( $_POST[‘shipping_postcode’] ) ? $_POST[‘shipping_postcode’] : ";
        $regex = '/^\d{5}$/';
        if ( ! preg_match( $regex, $billing_zip ) ) {
        wc_add_notice( 'Please enter a valid 5 digit billing Zip code', 'error' );
        }
        if ( ! preg_match( $regex, $shipping_zip ) ) {
        wc_add_notice( 'Please enter a valid 5 digit shipping Zip code', 'error' );
        }
        }
        add_action( 'woocommerce_checkout_process', 'soma_validate_us_zip' );

        Best Regards

Viewing 2 reply threads

Reply To: Need to limit the size Zip Code fields in checkout page

Your information:




Cancel