Sunday, January 10, 2016

Javascript to Force Phone Number Input Formatting (Quick and Dirty)

Javascrip Phone Number Format Forcer

One of the common issues with HTML forms is how to handle a variety of input from the user, while maintaining compatibility with the system that is the destination for the values from the form (e.g. a CRM system, a database, etc.)

I ran into this issue head-first at work, when we discovered that a specific CRM that our leads were being sent to required that phone numbers be in a specific format (###-###-####), but our form allowed users to input characters into the phone number field in whatever format they wanted. There are two main options here.

  • One, you can force users to enter their phone number in your format (break up the phone field into three separate fields, then use JS to concatenate the fields with dashes). I don't like this method, because it has the potential to confuse users and doesn't always work with browsers that store past field values.
  • A better method is to simply change the users input to the preferred format, after they have already entered it.

I'm still a novice when it comes to Javascript, but in about 15 minutes I had a solution that I was happy with and works perfectly. It uses plain vanilla Javascript (I'm a sucker for JQuery, but this is better for compatibility) and is reusable (just change the ID to match whatever the ID of your phone input field is). For my specific application, I used this for an embedded Caspio web form.

Javascript Code:


function Fix_Phone(){
 var phone_field_content = document.getElementById("InsertRecordPhone").value;
 var phone_numbers_only = phone_field_content.replace(/[^\d]/g,"");
 if (phone_numbers_only.length > 10){ // If user includes country code
  var country_code = phone_numbers_only.slice(0,1);
  var area_code = phone_numbers_only.slice(1,4);
  var main_num1 = phone_numbers_only.slice(4,7);
  var main_num2 = phone_numbers_only.slice(7,11);
  document.getElementById("InsertRecordPhone").value = (area_code+"-"+main_num1+"-"+main_num2);
 else {
  var area_code = phone_numbers_only.slice(0,3);
  var main_num1 = phone_numbers_only.slice(3,6);
  var main_num2 = phone_numbers_only.slice(6,10);
  document.getElementById("InsertRecordPhone").value = (area_code+"-"+main_num1+"-"+main_num2);


Further Notes:

Depending on your personal preference, you might want to add more to my code (e.g. validation of the number, warn user if number is not valid, etc).

No comments:

Post a Comment