Is there a quick way to set an HTML text input (<input type=text />) to only allow numeric keystrokes (plus ‘.’)?
Is there a quick way to set an HTML text input ( <input type=text
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
JavaScript
You can filter the input values of a text
<input>with the followingsetInputFilterfunction (supports Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, validity error message, and all browsers since IE 9):You can now use the
setInputFilterfunction to install an input filter:Apply your preferred style to the
input-errorclass. Here’s a suggestion:Note that you still must do server side validation!
Another caveat is that this will break the undo stack since it sets
this.valuedirectly. This means that CtrlZ will not work to undo inputs after typing an invalid character.Demo
See the JSFiddle demo for more input filter examples or run the Stack snippet below:
TypeScript
Here is a TypeScript version of this.
jQuery
There is also a jQuery version of this. See this answer.
HTML5
HTML5 has a native solution with
<input type="number">(see the specification and documentation). The documentation has a working demo of this input type.valueproperty, read thevalueAsNumberproperty of the input to get the typed value as a number rather than a string.<form>is recommended because validation is made easier this way; for example, pressing Enter will automatically show an error message if the value is invalid.checkValiditymethod or therequestSubmitmethod on the entire form in order to explicitly check the validity.requiredattribute in order to disallow an empty input.checkValiditymethod or thevalidityproperty on the input element itself in order to explicitly check the validity.reportValidityto show an error message and usesetCustomValidityto set your own message.This approach fundamentally has a different user experience: you are allowed to input invalid characters and the validation is performed separately. This has the benefit that the undo stack (CtrlZ) won’t break. Note that server-side validation must be performed, regardless, no matter which approach you choose.
But note that browser support varies:
step,minandmaxattributes.eandEinto the field. Also see the Q&A Why does the HTML input withtype="number"allow the lettereto be entered in the field?.Demo