Auto Format Phone Number JavaScript

Auto Format Phone Number JavaScript
Code Snippet:Simple Phone Formater
Author: Christophor Wilson
Published: April 8, 2024
Last Updated: April 8, 2024
Downloads: 97
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code snippet utilizes regular expressions (regex) to automatically format phone numbers on webpages accurately. It ensures correct formatting as users type, enhancing user experience and reducing input errors. You can integrate this code into any web form requiring phone number input, facilitating effortless and standardized data entry.

How to Create Auto Format Phone Number Javascript

1. First of all, load the Bootstrap and Font Awesome CSS by adding the following assets into the head tag of your HTML document.

<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css'>
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css'>

2. Include an input field for the phone number with an appropriate placeholder.

<div class="heading">
  <h1>Simple Phone Formater</h1>
  <h4>Automatically format US phone numbers using vanilla JavaScript.</h4>
</div>

<div class="container" id="app">
  
  <div class="form-group">
    <div class="input-group">
      <span class="input-group-addon"><span class="fa fa-phone"></span></span>
      <input type="tel" name="phone" id="phone" placeholder="(555) 555-5555" autocomplete="tel" maxlength="14" class="form-control" pattern="[(][0-9]{3}[)] [0-9]{3}-[0-9]{4}" required />
    </div>
  </div>
</div>

3. Optionally, add CSS styling to customize the appearance of your form.

.container {
  padding: 40px 80px 15px 80px;
  background-color: #fff;
  border-radius: 8px;
}

.heading h1 {
  background: -webkit-linear-gradient(#fff, #999);
  -webkit-text-fill-color: transparent;
  -webkit-background-clip: text;
  text-align: center;
  margin: 0 0 5px 0;
  font-weight: 900;
  font-size: 4rem;
  color: #fff;
}
.heading h4 {
  color: #a990cc;
  text-align: center;
  margin: 0 0 35px 0;
  font-weight: 400;
  font-size: 24px;
}

.form-group {
  margin-bottom: 25px;
}

4. Finally, add the following JavaScript code snippet to your HTML file or link it externally. This code listens for input events on the phone number field and formats the entered phone number accordingly.

document.getElementById('phone').addEventListener('input', function (e) {
  var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
  e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
});

That’s all! hopefully, you have successfully created functionality to auto-format phone numbers on your web form. If you have any questions or suggestions, feel free to comment below.

Leave a Comment