Reputation: 7953
How to do decimal validation using javascript?
there is a text box which should accept only 24.00 or 24 or any value less than 24.00
the text also must allow if 23.99 is entered.
could some one help me on this??
I tried this way,
if (document.forms[0].hours!= undefined) {
var val = document.forms[0].hours.value ;
if (val .match(/^\d{0,6}(?:\.\d{0,2})?$/)) {
alert("Invalid" +'${payType5Code}'+" Hours. The hours entered can not have more than 2 decimal places,and should be in the range of 0 to 24 ");
submitted=false;
return false;
}
}
thanks
Upvotes: 0
Views: 122
Reputation: 172588
You may try this:
var foo = document.getElementById('foo');
foo.addEventListener('input', function (prev) {
return function (evt) {
if (!/^\d{0,6}(?:\.\d{0,2})?$/.test(this.value)) {
this.value = prev;
}
else {
prev = this.value;
}
};
}(foo.value), false);
Upvotes: 1
Reputation: 6252
This can be done by simple regex expression.
val = "2.13"
if (!val.match(/^(\d{0,2})(\.\d{2})$/)) {
alert("sorry this is wrong");
} else {
alert("yeah this is true");
}
Check here for more ways..
Upvotes: 1