How7oHow7o
  • Home
  • Tools
    • All Tools
    • Image Tools
    • Text & String Tools
    • Video Tools
    • Developer Tools
    • PDF Tools
    • Calculators & More
  • Prank Screens
  • Learn
  • Blog
  • Contact
Reading: How to Set a Minimum Length for Phone Numbers in WooCommerce
Share
Notification Show More
Font ResizerAa
How7oHow7o
Font ResizerAa
  • Tools
  • Prank Screens
  • Learn
  • Blog
Search
  • Home
  • Tools
    • All Tools
    • Image Tools
    • Text & String Tools
    • Video Tools
    • Developer Tools
    • PDF Tools
    • Calculators & More
  • Prank Screens
  • Learn
  • Blog
  • Contact
Follow US
© 2024–2026 How7o. All rights reserved.
How7o > Free Laravel, PHP, WordPress & Server Tutorials > Web Development > How to Set a Minimum Length for Phone Numbers in WooCommerce
Web Development

How to Set a Minimum Length for Phone Numbers in WooCommerce

how7o
By how7o
Last updated: May 23, 2026
6 Min Read
Enforce a minimum phone-number length in WooCommerce checkout
SHARE

To enforce a minimum phone-number length in WooCommerce (e.g. exactly 11 digits for Bangladeshi or 10 for US/CA), hook woocommerce_checkout_process for server-side validation and use the pattern/maxlength input attributes for client-side UX. The server check is the one that actually enforces the rule; the client attributes give users instant feedback.

Contents
  • The complete snippet
  • What each piece does
  • Variations
  • Frequently asked questions
  • Related guides
  • References

Last verified: 2026-05-17 on WooCommerce 9.0 + WordPress 6.5. Originally published 2023-07-14, rewritten and updated 2026-05-17.

The complete snippet

// Server-side validation — the one that actually enforces the rule
add_action( 'woocommerce_checkout_process', function () {
    if ( isset( $_POST['billing_phone'] ) ) {
        $digits = strlen( preg_replace( '/[^0-9]/', '', wp_unslash( $_POST['billing_phone'] ) ) );

        if ( 11 !== $digits ) {
            wc_add_notice(
                __( '<strong>Phone number</strong> must be 11 digits long.', 'your-textdomain' ),
                'error'
            );
        }
    }
} );

// Client-side UX — instant feedback before submit
add_action( 'wp_footer', function () {
    if ( ! is_checkout() ) {
        return;
    } ?>
    <script>
        jQuery(function ($) {
            $('#billing_phone')
                .attr('pattern',   '[0-9]{11}')
                .attr('maxlength', '11')
                .attr('title',     'Phone number must be 11 digits');

            $(document).ajaxComplete(function (event, xhr, settings) {
                try {
                    if (
                        settings.url.indexOf('?wc-ajax=checkout') !== -1 &&
                        xhr.responseJSON.result === 'failure' &&
                        xhr.responseJSON.messages.toLowerCase().indexOf('phone') !== -1
                    ) {
                        $('#billing_phone_field')
                            .addClass('woocommerce-invalid woocommerce-invalid-required-field')
                            .removeClass('woocommerce-validated');
                    }
                } catch (e) { /* ignore */ }
            });
        });
    </script>
<?php } );

Drop this in your child theme’s functions.php or a small site-specific plugin. The server hook rejects invalid submissions; the footer script attaches client-side validation and visually marks the phone field as invalid when the server returns a phone-related error.

WooCommerce phone validation — server hook, client pattern attribute, AJAX failure highlighting

What each piece does

  • woocommerce_checkout_process — fires server-side during checkout submission. Adding an error notice here stops the order from completing.
  • preg_replace('/[^0-9]/', '', $phone) — strips formatting (spaces, dashes, plus signs) before counting digits, so +880 1234-567890 and 01234567890 are both valid.
  • pattern="[0-9]{11}" — HTML5 input pattern. The browser blocks submission with a built-in error message when the value doesn’t match.
  • maxlength="11" — caps typing at 11 characters in the input field itself.
  • The ajaxComplete handler — the WooCommerce checkout submits via Ajax, and on a server-side validation failure WC returns a JSON response with messages. We watch for phone-related failures and visually mark the field invalid so the error is easy to spot.

Variations

// Allow 10 OR 11 digits
$digits = strlen( preg_replace( '/[^0-9]/', '', wp_unslash( $_POST['billing_phone'] ) ) );
if ( ! in_array( $digits, [ 10, 11 ], true ) ) {
    wc_add_notice( __( 'Phone must be 10 or 11 digits.', 'your-textdomain' ), 'error' );
}

// Require a country prefix
if ( ! preg_match( '/^\+?880\d{10}$/', $_POST['billing_phone'] ) ) {
    wc_add_notice( __( 'Phone must start with +880 followed by 10 digits.', 'your-textdomain' ), 'error' );
}

Frequently asked questions

Why validate on both the server and the client?

Client-side validation (the pattern attribute) gives instant feedback before the form even submits — friendlier UX. Server-side validation (the woocommerce_checkout_process hook) is what actually enforces the rule, because client validation can be bypassed by anyone with DevTools. Always validate on the server; treat the client validation as a usability layer, not a security boundary.

How do I support multiple valid lengths (e.g. 10 or 11 digits)?

Change the strict != 11 check to !in_array($phone, [10, 11], true). For more nuance — different countries, different valid formats — drop your own validation entirely and use a library like libphonenumber. It parses, validates, and formats numbers per E.164 rules so you don’t have to maintain country-specific regexes.

Will this work on the WooCommerce Blocks (Cart/Checkout block) checkout?

The woocommerce_checkout_process hook fires on the legacy shortcode checkout. For the new Cart/Checkout blocks, validation hooks differ — register a Store API validation rule with woocommerce_store_api_checkout_update_order_from_request or use the extend API to attach field-level rules. The pattern from this guide still works on the shortcode checkout, which is what most existing stores still use.

Why use preg_replace('/[^0-9]/', '', ...) when checking length?

Customers often type formatting characters — spaces, dashes, parentheses, plus signs (+880-1234-567890). Counting the raw string would reject valid input. Stripping non-digits first means we count only the digits and ignore decoration. If you want to allow a leading +, adjust to preg_replace('/[^0-9+]/', '', ...).

Related guides

  • How to Remove Checkout Fields in WooCommerce
  • How to Rename Menu Items on the WooCommerce My Account Page
  • How to Add a Custom Fee in WooCommerce

References

WooCommerce woocommerce_checkout_process hook: woocommerce.com/document/customizing-the-checkout-field-using-actions-and-filters. WordPress wc_add_notice: woocommerce.github.io/code-reference. libphonenumber for PHP: github.com/giggsey/libphonenumber-for-php.

TAGGED:JavaScriptphpWooCommercewordpress

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
[mc4wp_form]
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Previous Article Use a JavaScript variable as an object key How to Use a Variable as an Object Key in JavaScript
Next Article Set A4 paper size in CSS for printing How to Set A4 Paper Size in CSS for Print
Leave a Comment

Leave a Reply Cancel reply

You must be logged in to post a comment.

You Might Also Like

Configure Nginx for WordPress in aaPanel (fix 404 permalinks)
Server Management

Configure Nginx for WordPress in aaPanel (Fix Permalink 404 Errors)

5 Min Read
Replace jQuery .each with vanilla JavaScript loops
Web Development

How to Replace jQuery’s .each() with Vanilla JavaScript

4 Min Read
WooCommerce add custom fee — woocommerce_cart_calculate_fees + WC()->cart->add_fee
Web Development

How to Add a Custom Fee (or Transaction Fee) in WooCommerce

8 Min Read
Break out of a jQuery .each() loop with return false
Web Development

How to Break Out of a jQuery .each() Loop

5 Min Read
How7oHow7o

Free browser-based tools, prank screens, and step-by-step tech tutorials. No signup, nothing uploaded.

  • Private by design — your files never leave your device
  • Instant — no signup, no install, no waiting
  • Always free — no trials, no watermarks, no paywalls

Tools

  • PDF Editor
  • Image Upscaler
  • JPEG Compressor
  • Password Generator
  • QR Code Generator
  • Video Trimmer
  • See all tools →

Pranks

  • Cracked Screen Prank
  • Fake Blue Screen (BSOD)
  • Fake Disk Format
  • Fake Low Battery
  • Fake Nintendo Switch Update Screen
  • Fake PlayStation Update Screen
  • See all prank screens →

Company

  • About Us
  • Blog
  • Contact
  • Privacy Policy
  • Terms of Service
  • Sitemap
© 2024–2026 How7o. All rights reserved.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?