Reputation: 3803
I have a text box where I restrict user from typing anything other than numeric values. Only 0-9 allowed using jQuery.
My code:
if (event.which < 46 || event.which > 59)
event.preventDefault();
Now, I want to allow a negative sign (only at beginning) with numeric like (-12,-13)
. I should restrict these scenarios (--1,-1-,1----)
. Only valid negative numbers should be allowed.
How can I do this using jQuery?
Upvotes: 1
Views: 3316
Reputation: 324630
Have you considered... not using jQuery for everything?
<input type="number" step="1" />
This will allow the user to type anything they want, but supporting browsers (all of them if they're up-to-date) will prevent the form from being submitted if the value is not a valid number.
Unsupporting (out-of-date) browsers will submit the form regardless, but that's fine because 1) You should be validating server-side anyway, and 2) any jQuery solution would fail if the user disables JavaScript, whereas this will work without JS in supporting browsers.
Upvotes: 1
Reputation: 856
you can use this validator: jquery.numeric
http://www.texotela.co.uk/code/jquery/numeric/
Upvotes: 1