<input type="tel"
id="phone"
name="phone"
placeholder="(234) 567-8900"
/>
body {
font-family: "Open Sans", sans-serif;
box-sizing: border-box;
}
input {
display: inline-block;
font-size: 18px;
padding: 10px 10px !important;
margin-top: 15px !important;
margin-bottom: 15px !important;
border: 1px solid #cdcdcd !important;
outline: none;
}
const phone = document.getElementById("phone")
phone.oninput = (e) => {
e.target.value = autoFormatPhoneNumber(e.target.value)
}
function autoFormatPhoneNumber(phoneNumberString) {
try {
var cleaned = ("" + phoneNumberString).replace(/\D/g, "");
var match = cleaned.match(/^(1|)?(\d{0,3})?(\d{0,3})?(\d{0,4})?$/);
var intlCode = match[1] ? "+1 " : "";
return [intlCode,
match[2] ? "(": "",
match[2],
match[3] ? ") ": "",
match[3],
match[4] ? "-": "",
match[4]].join("")
} catch(err) {
return "";
}
}
console.log(autoFormatPhoneNumber("+12345678900")); // => "+1 (234) 567-8900"
console.log(autoFormatPhoneNumber("2345678900")); // => "(234) 567-8900"
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.