Skip to content

Instantly share code, notes, and snippets.

@ivanmarkovich
Created May 6, 2019 12:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivanmarkovich/7081dd958eb57669ae3526b33f433904 to your computer and use it in GitHub Desktop.
Save ivanmarkovich/7081dd958eb57669ae3526b33f433904 to your computer and use it in GitHub Desktop.
Input Filter Function
// Restricts input for the given textbox to the given inputFilter.
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);
}
});
});
}
// Restrict input to digits and '.' by using a regular expression filter.
setInputFilter(document.getElementById("myTextBox"), function(value) {
return /^\d*\.?\d*$/.test(value);
});
Integer values (both positive and negative):
/^-?\d*$/.test(value)
Integer values (positive only):
/^\d*$/.test(value)
Integer values (positive and up to a particular limit):
/^\d*$/.test(value) && (value === "" || parseInt(value) <= 500)
Floating point values (allowing both . and , as decimal separator):
/^-?\d*[.,]?\d*$/.test(value)
Currency values (i.e. at most two decimal places):
/^-?\d*[.,]?\d{0,2}$/.test(value)
Hexadecimal values:
/^[0-9a-f]*$/i.test(value)
jQuery
There is also a jQuery version of this. See this answer or try it yourself on JSFiddle.
HTML 5
HTML 5 has a native solution with <input type="number"> (see the specification), but note that browser support varies:
Most browsers will only validate the input when submitting the form, and not when typing.
Most mobile browsers don't support the step, min and max attributes.
Chrome (version 71.0.3578.98) still allows the user to enter the characters e and E into the field. Also see this question.
Firefox (version 64.0) and Edge (EdgeHTML version 17.17134) still allow the user to enter any text into the field.
Try it yourself on w3schools.com.
More complex validation options
If you want to do some other validation bits and pieces, this could be handy:
https://gist.github.com/nbouvrette/84ef4f498ac06cdd5b60
http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
https://github.com/lockevn/html-numeric-input
https://github.com/jonstipe/number-polyfill
shareimprove this answer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment