About this snippet

Help users enter their phone number correctly without frustration. This script formats the input automatically as they type, adding parentheses and dashes, which prevents errors and ensures your data is consistent.

Size
987 bytes
Uses
HTML, CSS, JavaScript
Loads
Nothing external
Views
472
<div class="input-container">
  <label>Phone Number</label>
  <input type="tel" id="phoneInput" placeholder="(555) 123-4567" maxlength="14">
</div>
.input-container {
  font-family: system-ui, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  max-width: 300px;
  margin: 0 auto;
}
label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #374151;
}
input {
  width: 100%;
  padding: 12px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  font-size: 1rem;
  outline: none;
  box-sizing: border-box;
  transition: border-color 0.2s;
}
input:focus {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}
const phoneInput = document.getElementById("phoneInput");

phoneInput.addEventListener("input", function(e) {
  let 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] : "");
});
Esc
↑↓ moveEnter select

Start from a template

Open an .html file, or HTML, CSS, JS, Markdown, Less or TypeScript files. You can also drop them here. Styles and scripts go into their panes.

Share

Source

Keyboard shortcuts

Save