Last active
October 1, 2018 13:07
-
-
Save Postnov/e5852009b16bf56b2f2192136c2189ac to your computer and use it in GitHub Desktop.
Input mask number on pure 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
function mask(event, selector) { | |
var keyCode; | |
var input = document.querySelector(selector); | |
function maskInput(event) { | |
event.keyCode && (keyCode = event.keyCode); | |
var pos = this.selectionStart; | |
if (pos < 3) event.preventDefault(); | |
var matrix = "+0 (___) ___ __ __", | |
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 = ""; | |
} | |
if (input) { | |
input.addEventListener("input", maskInput, false); | |
input.addEventListener("focus", maskInput, false); | |
input.addEventListener("blur", maskInput, false); | |
input.addEventListener("keydown", maskInput, false) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment