Is there a quick way to set an HTML text input (<input type=text />
) to only allow numeric keystrokes (plus '.')?
相关问题
- Views base64 encoded blob in HTML with PHP
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
JavaScript
additional you could add comma, period and minus (,.-)
HTML
You can replace the Shurok function with:
Most answers here all have the weakness of using key- events.
Many of the answers would limit your ability to do text selection with keyboard macros, copy+paste and more unwanted behavior, others seem to depend on specific jQuery plugins, which is killing flies with machineguns.
This simple solution seems to work best for me cross platform, regardless of input mechanism (keystroke, copy+paste, rightclick copy+paste, speech-to-text etc.). All text selection keyboard macros would still work, and it would even limit ones ability to set a non-numeric value by script.
The best way (allow ALL type of numbers - real negative, real positive, iinteger negative, integer positive) is:
JavaScript
The
setInputFilter
function from the below script allows you to use any kind of input filter on a text<input>
, including various numeric filters. This will correctly handle Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, and all keyboard layouts. Works cross-browser and on mobile, IE 9+. Note that you still must do server side validation!Try it yourself on JSFiddle.
Usage:
Some regular expressions you might want to use for input filtering:
/^-?\d*$/
restricts input to integer numbers/^\d*$/
restricts input to unsigned integer numbers/^[0-9a-f]*$/i
restricts input to hexadecimal numbers/^-?\d*[.,]?\d*$/
restricts input to floating point numbers (allowing both.
and,
as decimal separator)/^-?\d*[.,]?\d{0,2}$/
restricts input to currency values (i.e. at most two decimal places)You might also want to restrict input to integer values up to a particular limit:
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. As an example, Firefox (as of version 63.0.3) still allows the user to enter 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:
So simple....
// In a JavaScript function (can use HTML or PHP).
In your form input:
With input max. (These above allows for a 12-digit number)