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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

I think the regex will not work if the text entered in the text box is 2 :)
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

4 Comments

thanks for the answer, the text box which i will be validating is created dynamically which means the text may or may not exist. so after finding the text box existence only will have to do the validation and alert the user if the value does not match.
@Anto:- So you have to put the check above this function for the existence of the text box. Rest the function will be same and it will work! :)
are you there? i have an issue with the above code.
@Anto:- What is the issue?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.