Created
July 18, 2022 19:14
-
-
Save cccamuseme/cfa57b2dc6129d3f9cc80e9fbe9108df to your computer and use it in GitHub Desktop.
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
// Restricts input for the given textbox to the given inputFilter function. | |
function setInputFilter(textbox, inputFilter, errMsg) { | |
["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop", "focusout"].forEach(function(event) { | |
textbox.addEventListener(event, function(e) { | |
if (inputFilter(this.value)) { | |
// Accepted value | |
if (["keydown","mousedown","focusout"].indexOf(e.type) >= 0){ | |
this.classList.remove("input-error"); | |
this.setCustomValidity(""); | |
} | |
this.oldValue = this.value; | |
this.oldSelectionStart = this.selectionStart; | |
this.oldSelectionEnd = this.selectionEnd; | |
} else if (this.hasOwnProperty("oldValue")) { | |
// Rejected value - restore the previous one | |
this.classList.add("input-error"); | |
this.setCustomValidity(errMsg); | |
this.reportValidity(); | |
this.value = this.oldValue; | |
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd); | |
} else { | |
// Rejected value - nothing to restore | |
this.value = ""; | |
} | |
}); | |
}); | |
} | |
setInputFilter(document.getElementById("input_21_4"), function(value) { | |
return /^\d*\.?\d*$/.test(value); // Allow digits and '.' only, using a RegExp | |
}, "Only digits and '.' are allowed"); | |
setInputFilter(document.getElementById("input_21_5"), function(value) { | |
return /^\d*\.?\d*$/.test(value); // Allow digits and '.' only, using a RegExp | |
}, "Only digits and '.' are allowed"); | |
setInputFilter(document.getElementById("input_21_6"), function(value) { | |
return /^\d*\.?\d*$/.test(value); // Allow digits and '.' only, using a RegExp | |
}, "Only digits and '.' are allowed"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment