0

How to allow only Numerical number of range 0-999 using jQuery? If number is out of range it should give an error? I tried in a general way but it's not working. The code is given below.

function checkIsNumeric(value){
        if(isNaN(value) && (value>1000 || value<0)) {
            return 0;
        }

        return true;
    }
3
  • Your question is not very clear. What kind of an error should it give? Commented Jun 6, 2013 at 18:22
  • It should display error such as "Enter value of range 0-999" Commented Jun 6, 2013 at 18:23
  • 2
    Just use u_mulder's answer and do something like: if(checkIsNumberic(your_var)){ /* is a number */ } else { $('.your-error-div').text('Enter value of range 0-999'); } Commented Jun 6, 2013 at 18:27

3 Answers 3

2
function checkIsNumeric( value ){
    if ( isNaN( value ) || value > 999 || value < 0 ) {
        return 0;
    }

    return true;
}

Or:

function checkIsNumeric( value ){
    return ( isNaN( value ) || value > 999 || value < 0 )? 0 : true;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Couple issues.

value > 1000 will not capture values of 1000 which you don't want. Change that to >=.

So let's say we make the above change and put in a value of 1000. isNaN will return false which is what we would expect. (value>=1000 || value<0) will return true which is also what we want. However, since you and'ed these two together the result will be false (false && true == false) and the if-statement will be ignored.

What you want is something more like this:

function checkIsNumeric( value ) {
    if( isNaN( value ) || value >= 1000 || value < 0 )
    {
        return false;
    }

    return true;
}

Comments

0
function checkIsNumeric(value){
    if(value > 0 && value < 1000){
        alert('Within range.')
        return;
    }
    alert('Enter value between 0-999.');
}

You can also turn the parameter into an integer by:

parseInt(value, 10);

Or float:

parseFloat(value);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.