It's slightly tricky to decide exactly what the user interface should be. Although they can see the spaces they can't delete them, which if the normal browser editing were allowed they would be able to do.
We also want to ignore non-digit input and not allow the total number of digits to go beyond 10.
This snippet does these things by having the input as type normal text rather than number and testing each key input to see if it should be included or not and rewriting the value each time with the spaces inserted if required.
const phone = document.querySelector('.phone');
phone.addEventListener("keyup", function(e) {
let txt = this.value.replace(/\D/g, '');
let newtxt = '';
//now copy the number inserting a space where needed
for (let i = 0; i < Math.min(txt.length, 10); i++) {
newtxt += txt[i];
if ((i == 2) || (i == 5)) {
newtxt += ' ';
}
}
if (newtxt[newtxt.length - 1] == ' ') newtxt = newtxt.substring(0, newtxt.length - 1);
this.value = newtxt;
});
<input class="phone">
There needs to be further thought as to whether some refinements to the user interface would be a good idea. For example:
- re-positioning the cursor (at the moment it goes to the end of the
string after each input which the user maybe won't expect if they are
editing part way along the number)
- and it's probably a moot point as to whether it is best to show
briefly a character that is illegal, to sort of reassure the user
they have indeed pressed a key, or whether that character should
never show.
Before submitting the value to the backend, remember to remove the spaces:
phone.value.replace(/\D/g, '');