Московский номер телефона
Tue Feb 08 2022 15:12:05 GMT+0000 (Coordinated Universal Time)
Saved by
@Evgeniya
<input id="online_phone" name="phone" type="tel" maxlength="50" autofocus="autofocus"
required="required" value="+7(___)___-__-__"
pattern="\+7\s?[\(]{0,1}9[0-9]{2}[\)]{0,1}\s?\d{3}[-]{0,1}\d{2}[-]{0,1}\d{2}"
placeholder="+7(___)___-__-__">
function setCursorPosition(pos, e) {
e.focus();
if (e.setSelectionRange) e.setSelectionRange(pos, pos);
else if (e.createTextRange) {
var range = e.createTextRange();
range.collapse(true);
range.moveEnd("character", pos);
range.moveStart("character", pos);
range.select()
}
}
function mask(e) {
//console.log('mask',e);
var matrix = this.placeholder,// .defaultValue
i = 0,
def = matrix.replace(/\D/g, ""),
val = this.value.replace(/\D/g, "");
def.length >= val.length && (val = def);
matrix = matrix.replace(/[_\d]/g, function (a) {
return val.charAt(i++) || "_"
});
this.value = matrix;
i = matrix.lastIndexOf(val.substr(-1));
i < matrix.length && matrix != this.placeholder ? i++ : i = matrix.indexOf("_");
setCursorPosition(i, this)
}
window.addEventListener("DOMContentLoaded", function () {
var input = document.querySelector("#online_phone");
input.addEventListener("input", mask, false);
input.focus();
setCursorPosition(3, input);
});
content_copyCOPY
https://htmlweb.ru/html/form/form_input_pattern.php
Comments