Is there any existing jQuery functionality that can test if characters entered into a textbox are either numeric, or valid in a number?
Such as
.00 or 0.00, but not 0.00.00 or 0a
What I’d like to do is catch any invalid characters before they appear in the textbox.
If it’s not possible with jQuery, what’s the best way to approach this?
I know with JavaScript I can test isNaN() and then return false, but that’s going to start getting hairy when I have to account for all possible keystrokes.
It’s a little tricky, since you want to make sure you can enter all numbers left to right, but something like this:
Try it out with this jsFiddle
Note how I’m checking the number from left to right. This means that
+must be valid. Also5.must be valid, or you could never enter5.0or+5.Now the above has some major issue (try the arrow keys).
Here’s a slightly more elegant solution that accommodates a default value as well:
Try it out with this jsFiddle
Example HTML for the above:
Note how when you use
.test()you have to test from the beginning^to the end$.