I wanted to restrict the user from entering the values from a specific range. So i wrote the following code using JQuery 1.7.1
var reg = /^[0-9]{1,4}[.]{0,1}[0-9]{0,2}$/g;
$("#txt" + filterID).bind('keypress', function (e) {
var nn = $("#txtValues");
var strValue = nn[0].value.toString();
strValue = $.trim(strValue);
var bool = reg.test(strValue);
if (strValue.length == 0 && !((e.which < 48 || e.which > 57) && e.which != 46 && e.which != 8 && e.which != 0)) {
return true;
}
else if (bool) {
return true;
}
else {
e.preventDefault();
}
});
When i test the input box, it’s not working as expected. It supposed to allow a floating point number with 2 digits after decimal point.Some of the valid formats are
1
1.
1.0
0
1.20
0.0
1.23
123.43
1234.12
I am not sure, where I have done wrong. After recognizing 1. it’s getting failed. Can anybody help me to identify the issue?
The
keypressevent is fired before the value has updated. Use the following code, which translates theevent.whichproperty to a character using theString.fromCharCodemethod.Non-printable keystrokes will generate a
event.whichof zero, which is certainly not a digit or dot.As for the RegExp, you have to group the expression after the dot, and add a questionmark, to say “Let this group match be optional”.
The pattern will match the following: