Tuesday, 1 October 2019

Format Phone Number in JavaScript for internal use

I am trying to format phone numbers for internal use, I found this code off another thread and it seems really close to what I want to use but is lacking

function phoneFormatter() {
  $('.phone').on('input', function() {
    var number = $(this).val().replace(/[^\d]/g, '')
    if (number.length == 7) {
      number = number.replace(/(\d{3})(\d{4})/, "$1-$2");
      //US & Canada Formatting
    } else if (number.length == 10) {
      number = number.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
    }
      //France Formatting
      else if (number.length == 11) {
      number = number.replace(/(\d{2})(\d{1})(\d{2})(\d{2})(\d{2})(\d{2})/, "+$1 $2 $3 $4 $5 $6");
    }
      //German Formattiing 
      else if (number.length == 13) {
      number = number.replace(/(\d{2})(\d{3})(\d{8})/, "+$1 $2 $3");
    }
    $(this).val(number)
  });
};

$(phoneFormatter);
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
 <p><label>Phone Number<br>               
 <input name="phone"    class="phone" id="phone"     type="text"     required></label></p>

</body>
</html>

After reading https://en.wikipedia.org/wiki/National_conventions_for_writing_telephone_numbers

is there a library or a set of code that already has the proper formatting for all the countries? I lack the Javascript knowledge to write all that myself.



from Format Phone Number in JavaScript for internal use

No comments:

Post a Comment