How to set a minimum length for phone numbers in WooCommerce?

I have a WooCommerce shop, I often encounter customers who enter incorrect phone numbers with fewer digits. This leads to communication difficulties and can affect order processing. I would like to set a minimum length for phone numbers. I only sell products within my country, and the phone numbers are always 11 digits long. Therefore, I want to enforce this rule to ensure that customers provide a valid 11-digit phone number during the checkout process. How can I configure WooCommerce to set a minimum length of 11 digits for phone numbers and display an error message if the customer’s input does not meet this requirement?

To set a minimum length of 11 digits for phone numbers in WooCommerce and display an error message if the input does not meet this requirement, you can use the following code:

// Limit Mobile Number
add_action('woocommerce_checkout_process', function() {
    if (isset($_POST['billing_phone'])) {
        $phone = strlen(preg_replace('/[^0-9]/', '', $_POST['billing_phone']));
        if ($phone != 11) {
            wc_add_notice( __( '<strong>Phone mumber</strong> must be 11 digits long.' ), 'error' );
        }
    }
});


add_action('wp_footer', function(){ ?>
<script>
    jQuery( 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 ) {
                jQuery('#billing_phone_field').addClass('woocommerce-invalid woocommerce-invalid-required-field').removeClass('woocommerce-validated');
            }
        }
        catch(e){
            console.log( e );
        }
    });
    
    jQuery( document ).ready( function( $ ) {
        $( '#billing_phone' )
        .attr( 'pattern', '[0-9]{11}' )
        .attr( 'maxlength', '11' )
        .attr( 'title', 'Phone number must be 11 digits' );
    });
</script>
<?php });

This code includes two actions. The first action, woocommerce_checkout_process, checks if the billing_phone field is set in the form submission. It then counts the number of digits in the phone number and displays an error notice if it is not 11 digits long.

The second action, wp_footer, includes JavaScript code to enhance the validation. It uses jQuery to add a pattern, maximum length, and a title attribute to the billing_phone input field. This ensures that users are prompted to enter an 11-digit phone number and provides them with an error message if the input does not meet the requirement.

Remember to add this code to your theme’s functions.php file or a custom plugin to apply the changes.