Need to limit the size Zip Code fields in checkout page

Bob Byers February 25, 2023 at 5:56 pm

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?

Replies (3)

  1. Bob Byers February 25, 2023 at 5:56 pm

    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?

  2. Spiracle Themes February 26, 2023 at 12:59 pm

    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

  3. Bob Byers February 27, 2023 at 7:18 pm
    This reply has been marked as private.
  4. Spiracle Themes February 28, 2023 at 6:12 am

    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

Post a Reply

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