I have the script below, which I use to validate input to validate a textbox for no text, and it also usefully doubles to only allow a number between 0 and 10 with up to 3 decimal places.
$('.sourceValidation').keyup(function () {
if (!this.value.match(/^(([0-9]|10)(\.\d{1,3})?)?$/)) {
this.value = this.value.replace(/[^0-9\.]/g, '').substring(0,5);}})
I am not entirely sure of this code, but how do I rework it so that it will validate an input between 0 and 99 (whole numbers only), no text, no decimal points.
$('.sourceValidation').keyup(function () {
if (!this.value.match(/^([0-9]{0,2})$/)) {
this.value = this.value.replace(/[^0-9]/g, '').substring(0,2);
}
});
The key part is to change the regex from
/^(([0-9]|10)(\.\d{1,3})?)?$/
to
/^([0-9]{0,2})$/
..which is a regex which will allow 0, 1 or 2 digits. It will however allow leading zeroes eg 01
, 09
- or even 00
. I don't know if this is acceptable in your situation.
Updated fiddle
The replace
function is saying [^0-9]/g
- which means - replace anything that is not (^
) a digit (0-9
) and do it through the whole string (g
- global). It is then trimming it to 2 characters max (substring(0,2)
).
The regular expression you need to accept only 0 to 99 without anything else is
/^[0-9]{1,2}$/
This means : Accept digits from '0' to '9', 1 or 2 times.
Note that your code does not contain any jquery, this seems to be pure javascript. <-- Edit : this I take back. My bad.
Please find the working version of jquery below
[http://jsfiddle.net/jQmR3/][1]
This allows users to type numbers only
if ($.inArray(charpressed, alpha) > -1) {
return false;
}
You can add what characters you need to allow in the array there