Search code examples
javascriptformatting

Format a phone number as a user types using pure JavaScript


I've got an input field in the body of my document, and I need to format it as the user types. It should have parenthesis around the area code and a dash between the three and four digits after that.

Ex: (123) 456 - 7890

As the user types it should look something like:

(12
(123)
(123) 456
(123) 456 - 78
(123) 456 - 7890


Solution

  • New ES 2024 Answer

    It's even simpler now.

    HTML

    <input type="tel" id="phone" placeholder="(123) 456 - 7890" maxlength="16" />
    

    JS

    window.addEventListener('load', () => {
      const phoneInput = document.querySelector('#phone');
      phoneInput.addEventListener('keydown', disallowNonNumericInput);
      phoneInput.addEventListener('keyup', formatToPhone);
    });
    
    const disallowNonNumericInput = (evt) => {
      if (evt.ctrlKey) { return; }
      if (evt.key.length > 1) { return; }
      if (/[0-9.]/.test(evt.key)) { return; }
      evt.preventDefault();
    }
    
    const formatToPhone = (evt) => {
      const digits = evt.target.value.replace(/\D/g,'').substring(0,10);
      const areaCode = digits.substring(0,3);
      const prefix = digits.substring(3,6);
      const suffix = digits.substring(6,10);
    
      if(digits.length > 6) {evt.target.value = `(${areaCode}) ${prefix} - ${suffix}`;}
      else if(digits.length > 3) {evt.target.value = `(${areaCode}) ${prefix}`;}
      else if(digits.length > 0) {evt.target.value = `(${areaCode}`;}
    };
    

    Very Old ES5 Answer

    You can do this using a quick javascript function.

    If your HTML looks like:
    <input type="text" id="phoneNumber"/>

    Your JavaScript function can simply be:

    // A function to format text to look like a phone number
    function phoneFormat(input){
            // Strip all characters from the input except digits
            input = input.replace(/\D/g,'');
            
            // Trim the remaining input to ten characters, to preserve phone number format
            input = input.substring(0,10);
    
            // Based upon the length of the string, we add formatting as necessary
            var size = input.length;
            if(size == 0){
                    input = input;
            }else if(size < 4){
                    input = '('+input;
            }else if(size < 7){
                    input = '('+input.substring(0,3)+') '+input.substring(3,6);
            }else{
                    input = '('+input.substring(0,3)+') '+input.substring(3,6)+' - '+input.substring(6,10);
            }
            return input; 
    }
    

    Of course, you'll need an event listener:

    document.getElementById('phoneNumber').addEventListener('keyup',function(evt){
            var phoneNumber = document.getElementById('phoneNumber');
            var charCode = (evt.which) ? evt.which : evt.keyCode;
            phoneNumber.value = phoneFormat(phoneNumber.value);
    });
    

    And unless you're okay storing phone numbers as formatted strings (I don't recommend this), you'll want to purge the non-numeric characters before submitting the value with something like:
    document.getElementById('phoneNumber').value.replace(/\D/g,'');

    If you'd like to see this in action with bonus input filtering, check out this fiddle:
    http://jsfiddle.net/rm9vg16m/

    // Format the phone number as the user types it
    document.getElementById('phoneNumber').addEventListener('keyup', function(evt) {
      var phoneNumber = document.getElementById('phoneNumber');
      var charCode = (evt.which) ? evt.which : evt.keyCode;
      phoneNumber.value = phoneFormat(phoneNumber.value);
    });
    
    // We need to manually format the phone number on page load
    document.getElementById('phoneNumber').value = phoneFormat(document.getElementById('phoneNumber').value);
    
    // A function to determine if the pressed key is an integer
    function numberPressed(evt) {
      var charCode = (evt.which) ? evt.which : evt.keyCode;
      if (charCode > 31 && (charCode < 48 || charCode > 57) && (charCode < 36 || charCode > 40)) {
        return false;
      }
      return true;
    }
    
    // A function to format text to look like a phone number
    function phoneFormat(input) {
      // Strip all characters from the input except digits
      input = input.replace(/\D/g, '');
    
      // Trim the remaining input to ten characters, to preserve phone number format
      input = input.substring(0, 10);
    
      // Based upon the length of the string, we add formatting as necessary
      var size = input.length;
      if (size == 0) {
        input = input;
      } else if (size < 4) {
        input = '(' + input;
      } else if (size < 7) {
        input = '(' + input.substring(0, 3) + ') ' + input.substring(3, 6);
      } else {
        input = '(' + input.substring(0, 3) + ') ' + input.substring(3, 6) + ' - ' + input.substring(6, 10);
      }
      return input;
    }
    Enter a phone number here: <input type="text" id="phoneNumber" onkeypress="return numberPressed(event);" />