Created
October 13, 2019 14:46
-
-
Save RiodeJaneiroo/58ce0528eeb95e653cf3f5bc9cfd0139 to your computer and use it in GitHub Desktop.
[Mask input phone] pure JS #mask #js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
window.addEventListener("DOMContentLoaded", function() { | |
[].forEach.call( document.querySelectorAll('input.wpcf7-tel'), function(input) { | |
var keyCode; | |
function mask(event) { | |
event.keyCode && (keyCode = event.keyCode); | |
var pos = this.selectionStart; | |
if (pos < 3) event.preventDefault(); | |
var matrix = "+7 (___) ___-__-__", | |
i = 0, | |
def = matrix.replace(/\D/g, ""), | |
val = this.value.replace(/\D/g, ""), | |
new_value = matrix.replace(/[_\d]/g, function(a) { | |
return i < val.length ? val.charAt(i++) || def.charAt(i) : a | |
}); | |
i = new_value.indexOf("_"); | |
if (i != -1) { | |
i < 5 && (i = 3); | |
new_value = new_value.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 = new_value; | |
if (event.type == "blur" && this.value.length < 5) this.value = "" | |
} | |
input.addEventListener("input", mask, false); | |
input.addEventListener("focus", mask, false); | |
input.addEventListener("blur", mask, false); | |
input.addEventListener("keydown", mask, false) | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment