WooCommerce: Allow only Numbers in a Phone Number Field on the Checkout Page

In this tutorial, we’ll learn how to restrict the phone number field on the WooCommerce checkout page to accept only numeric input. This customization ensures that customers can only enter numbers in the phone number field, enhancing data accuracy and usability during the checkout process.

/**
* Snippet Name:  Restrict Phone Number Field to Numeric Input
* Snippet Author:  wpsnippets.dev
*/

//adding script to footer - Restrict Phone Number Field to Numeric Input
function wps_input_numbers_only_to_phone_field(){
   ?>
   <script>
      jQuery(document).ready(function($) {
        $('#billing_phone').on('input', function() {  // Function to allow only numbers in the phone field
          var sanitized = $(this).val().replace(/[^0-9]/g, '');   // Remove non-numeric characters from input value
          $(this).val(sanitized); // Update input value with sanitized version
        });
      });
   </script>
   <?php
}
add_action('wp_footer', 'wps_input_numbers_only_to_phone_field');

Code Explanation

  • This code snippet utilizes JavaScript to restrict the input of the phone number field only to accept numeric characters. It targets the phone number field by its ID (#billing_phone) and listens for input events. When a user types in the field, any non-numeric characters are removed from the input value, ensuring that only numbers remain.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top