0

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

Java Questions
  • 7,813
  • 41
  • 118
  • 176

2 Answers2

1

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);​

JS FIDDLE DEMO

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

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..

Community
  • 1
  • 1
Avinash Babu
  • 6,171
  • 3
  • 21
  • 26