<script>window.onload=function(){
document.getElementById('her').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] : '');
});
}
</script>
<script>document.addEventListener("DOMContentLoaded", function() {
var input = document.querySelector(".maskphone");
input.addEventListener("input", mask);
input.addEventListener("focus", mask);
input.addEventListener("blur", mask);
/***/
function mask(event) {
var blank = "+_ (___) ___-__-__";
var i = 0;
var val = this.value.replace(/\D/g, "").replace(/^8/, "7"); // <---
this.value = blank.replace(/./g, function(char) {
if (/[_\d]/.test(char) && i < val.length) return val.charAt(i++);
return i >= val.length ? "" : char;
});
if (event.type == "blur") {
if (this.value.length == 2) this.value = "";
} else {
setCursorPosition(this, this.value.length);
}
};
/***/
function setCursorPosition(elem, pos) {
elem.focus();
if (elem.setSelectionRange) {
elem.setSelectionRange(pos, pos);
return;
}
if (elem.createTextRange) {
var range = elem.createTextRange();
range.collapse(true);
range.moveEnd("character", pos);
range.moveStart("character", pos);
range.select();
return;
}
}
});
</script>
<input class="maskphone">
const addInputMaskPhone = () => {
$(document)
.on('input', '.js-input-phone', maskPhone)
.on('focus', '.js-input-phone', maskPhone)
.on('blur', '.js-input-phone', maskPhone)
.on('keydown', '.js-input-phone', maskPhone)
}
let keyCode
function maskPhone(event) {
event.keyCode && (keyCode = event.keyCode)
var pos = this.selectionStart
if (pos < 3) event.preventDefault()
const matrix = '+7 (___) ___-__-__'
let i = 0
const def = matrix.replace(/\D/g, '')
const val = this.value.replace(/\D/g, '')
let newValue = matrix.replace(/[_\d]/g, function (a) {
return i < val.length ? val.charAt(i++) || def.charAt(i) : a
})
i = newValue.indexOf('_')
if (i !== -1) {
i < 5 && (i = 3)
newValue = newValue.slice(0, i)
}
var reg = matrix
.substr(0, this.value.length)
.replace(/_+/g, function (a) {
return '\\d{1,' + a.length + '}'
})
.replace(/[+()]/g, '\\$&')
reg = new RegExp('^' + reg + '$')
if (
!reg.test(this.value) ||
this.value.length < 5 ||
(keyCode > 47 && keyCode < 58)
)
this.value = newValue
if (event.type === 'focusout' && this.value.length < 18) this.value = ''
}
addInputMaskPhone()