I’m trying to find a way to validate a text input on key press, I want to allow numbers only inside my text input including decimals.
I was taking the approach of using jQuery.keydown, and checking what the key was and using event.preventDefault() if the key was not in the allowed list. But since then I’ve read that keys aren’t consistent throughout browsers and I’m also worries about different OS’s.
I’ve come across this question but I’m not fluent in regex and not sure whether this would suit my needs:
jquery – validate characters on keypress?
With that approach a regex that expects 00.00 would stop the user when 00. is typed in since the regex is checked upon key up.
Thanks
You should not rely on key events as that would mean the validation would fail if the user does a right-click -> paste with invalid characters.
What you should instead do is use something like zurb’s
textchangedevent – which will accurately trigger regardless of the mode of input (key, paste, drag and drop, whatever)http://www.zurb.com/playground/jquery-text-change-custom-event
Inside your
textchangedhandler, you can put in the appropriate regex to deal with decimals.