Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save v-vashchenko/bcd928548389698103f17715d7cea32e to your computer and use it in GitHub Desktop.
Save v-vashchenko/bcd928548389698103f17715d7cea32e to your computer and use it in GitHub Desktop.
custom textInput filter JS
//custom textInput filter.
function setInputFilter(textbox, inputFilter) {
["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function (event) {
textbox.addEventListener(event, function () {
if (inputFilter(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
}
});
});
}
//usage example
setInputFilter(document.getElementById("salary-c"), function (value) {
return /^-?\d*$/.test(value); //ofc regex
});
module.exports = setInputFilter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment