I want a regular expression for a textbox which allows only 3 digits and passes following criterias:
- Only digits (234 or 123) or
- Only one decimal at the end (55.1)
- Should not allow spaces
- If decimal is used then there should be a number after/before decimal as well (555. or 12. or .12 should not be allowed)
I have following RE which works partially:
/^\d{0,3}$|^\d{0,2}[\.]\d{1}$/
Any help in modifying this ?
Looks like problem is additional:
I am using the code at keypress. So it validates each pressed value at key press.
if (window.event) {
knum = e.keyCode;
}
else if (e.which) {
knum = e.which;
}
kchar = String.fromCharCode(knum);
numcheck = /^\d{0,3}$|^\d{0,2}[\.]\d{1}$/;
alert(numcheck.test(kchar));
It returns false for any decimal key press. Even if I enter 55 and then try a decimal in middle to make it 5.5, ite returns false.
You need at least 1 digit, but 3 at most:
\d{1,3}OR
There have to be at least 1 but no more than 2 digits before and 1 after the decimal:
\d{1,2}[.]\dSo these combined:
/(^\d{1,3}$|^\d{1,2}[.]\d$)/UPDATE:
You are testing the character which was added on the keypress event, not the full value of the input field. This would never have the expected result.