tags:

views:

20

answers:

3

Hi all,

I want numeric javascript validation for marks field. Marks entered should be out of 5 means user can enter upto 5 marks not more than that. marks may be in decimal like 4.25 after decimal there should be 2 digits can any one help me..

+1  A: 

The simplest way is probably value.toString().match(/^[0-5](\.\d{1,2})?$/). Generally you want to avoid regular expressions, but this will save you several otherwise exhaustive steps to validate the format of the number.

mway
@Sachin Shanbhag's answer is a better idea.
mway
+1  A: 

Check this code -

if( Number(str) < 0 || Number(str).toFixed(2) > 5 ) {
    //Throw error
}

where str is your value to be validated.

Sachin Shanbhag
A: 

Mark: <input type="text" id="mark" onBlur="validateMark()">

function validateMark() {
    var val = document.getElementById('mark').value;
    if (!val.match(/^[0-5](\.\d{1,2})?$/)) {
        alert("Invalid mark: " + val);
    }
}
bemace