Soma Pro Theme Help Premium theme

Need to limit the size Zip Code fields in checkout page

BB Started by Bob Byers · February 25, 2023 at 5:56 pm · 3 replies 0 voices Last reply 3 years, 4 months ago
BB
Bob Byers Original poster Member
#1

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?

ST
Spiracle Themes Original poster
#2

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

ST
Spiracle Themes Original poster
#4

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

Join the conversation. Be kind — this is a public forum.

Replying to Need to limit the size Zip Code fields in checkout page

By posting, your reply becomes public (unless marked private).