Despite us having Pristine/Parsley for error validation, somtimes clients want the phone number to automatically format. Here’s how to do that.

This should work on BS5 sites with no addition, as it’s in vanilla javascript. To make it work in older bootstrap sites that use jQuery, you will need to swap Uglify out for Terser in your package.json.

Script.js file

  //format text input as phone number (XXX) XXX-XXXX
  const isNumericInput = (event) => {
    const key = event.keyCode;
    return ((key >= 47 && key <= 57) || (key >= 96 && key <= 105)
    );
  };

  const isModifierKey = (event) => {
    const key = event.keyCode;
    return (event.shiftKey === true || key === 35 || key === 36) || // Allow Shift, Home, End
      (key === 8 || key === 9 || key === 13 || key === 46 || key === 189) || // Allow Backspace, Tab, Enter, Delete
      (key > 36 && key < 41) || // Allow left, up, right, down
      (
        // Allow Ctrl/Command + A,C,V,X,Z
        (event.ctrlKey === true || event.metaKey === true) &&
        (key === 65 || key === 67 || key === 86 || key === 88 || key === 90)
      )
  };

  const enforceFormat = (event) => {
    // Input must be of a valid number format or a modifier key, and not longer than ten digits
    if(!isNumericInput(event) && !isModifierKey(event)){
      event.preventDefault();
    }
  };

  const formatToPhone = (event) => {
    if(isModifierKey(event)) {return;}

    const target = event.target;
    const input = event.target.value.replace(/\D/g,'').substring(0,10); 
    const areaCode = input.substring(0,3);
    const middle = input.substring(3,6);
    const last = input.substring(6,10);

    if(input.length > 6){ target.value = `(${areaCode}) ${middle}-${last}`;}
    else if(input.length >= 3){ target.value = `(${areaCode}) ${middle}`;}
    else if(input.length > 0){ target.value = `(${areaCode}`;}
  };

  document.querySelectorAll('[type="tel"]').forEach((phone)=>{
    phone.addEventListener('keydown', enforceFormat, false);
    phone.addEventListener('keyup', formatToPhone, false);
  });

Example Sites

Tags: scripts, js, vanilla javascript, form