Format billing phone number on WooCommerce checkout

19
February 16, 2019, at 03:20 AM

For the WooCommerce checkout billing field, how can I make this field require 9 numbers and insert dashes for proper phone formatting? For example, instead of typing out 3053453212 in the phone number field, it displays: (305-345-3212)

Answer 1

Based on "Formatting a phone number in a form using jquery" answer code, here is the way to format the Woocommerce billing phone:

add_action('wp_footer', 'format_checkout_billing_phone');
function format_checkout_billing_phone() {
    if ( is_checkout() && ! is_wc_endpoint_url() ) :
    ?>
    <script type="text/javascript">
    jQuery( function($){
        $('#billing_phone').on( 'input focusout', function() {
            var p = $(this).val();
            p = p.replace(/[^0-9]/g, '');
            p = p.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
            $(this).val(p);
        });
    });
    </script>
    <?php
    endif;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Answer 2

You can try this

   /** 
    *  Require 9 digit number. Format to 000-000-0000 at submission
    *  stackoverflow/54700465
    */
    add_filter( 'woocommerce_billing_fields', 'wc_filter_phone', 10, 1 );
            function wc_filter_phone( $address_fields ) {
                $address_fields['billing_phone']['min-lenght="9"'];
                $format_number = preg_replace("/^(\d{3})(\d{3})(\d{4})$/", "$1-$2-$3", $address_fields);
            return $format_number;
    }
    // End
READ ALSO
FPDI (or Adobe) is sending wrong data to the printer, so the PDF prints out as A4 size

FPDI (or Adobe) is sending wrong data to the printer, so the PDF prints out as A4 size

I am using FPDI (v1) to generate a PDF form with some values added dynamically from the database

16
Adding validation to memberpress custom fields?

Adding validation to memberpress custom fields?

I have a field that the user must fill in with a predefined formatI would like to validate it before the data is saved

14
pChart remove Y axis tick

pChart remove Y axis tick

Need to remove ticks from pChart library, or make them same color as background (white)

18
Write permission denied on Apache2 / Debian 9

Write permission denied on Apache2 / Debian 9

I have a VPS with apache2 php-fpm running prestashop, it's been working for years, but out of a sudden, prestashop is having trouble with permissions

40