The billing phone number field on the WooCommerce checkout page is sometimes hard to read. So we can format it by adding 2 dashes (-) for readability, it’s called masking.
The code below shows it. We can also mask the shipping field using the same method.
function sefatun_phone_field_formating( $fields ) {
$fields['billing']['billing_phone']['placeholder'] = '123-456-7890'; //Remove this line if you have placeholder or style
$fields['billing']['billing_phone']['maxlength'] = 12; // 123-456-7890 total 12 characters in here, including dashes.
return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'sefatun_phone_field_formating' );
function sefatun_phone_field_mask() {
wc_enqueue_js( "
$('#billing_phone') //Checkout form billing phone field input css id
.keydown(function(e) {
var key = e.which || e.charCode || e.keyCode || 0;
var phone = $(this);
if (key !== 8 && key !== 9) {
if (phone.val().length === 3) {
phone.val(phone.val() + '-'); // adding dash after 3 characters
}
if (phone.val().length === 7) {
phone.val(phone.val() + '-'); // adding dash after 7 characters
}
}
return (key == 8 ||
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
});
" );
}
add_action( 'woocommerce_after_checkout_form', 'sefatun_phone_field_mask' );