0

I have written a regular expression for the quantity and the maximum they can order is 500 for each (summer, autumn, winter). The expression is -

 var chkquantity = ^([1-9]?\d|[1-4]\d{2}|500)$/ 

I'm not sure if the test is correct -

if ((chkquantity.test(quantity)== false){
  alertmsg = alertmsg + "Please limit each magazine to 500 copies or less:" + "\n";
} 

?

4
  • 5
    Why not just convert it to a number and compare it to 500? Commented Feb 15, 2013 at 17:40
  • I'm not sure what you mean? sorry i'm a complete beginner and i am struggling :( Commented Feb 15, 2013 at 17:42
  • @user2073133 If quantity is a string that's really a number, you can just do something in javascript like parseInt(quantity) and then check if it's > 500 Commented Feb 15, 2013 at 17:45
  • I guess your expression should be /^([1-9]|[1-9][0-9]|[1-4][0-9][0-9]|500)$/. Commented Feb 15, 2013 at 18:04

3 Answers 3

1

If you are dealing with numbers, deal with them as numbers.

if (Number(quantity) > 500) {
    alertmsg = alertmsg + "Please limit each magazine to 500 copies or less:" + "\n";
}
Sign up to request clarification or add additional context in comments.

1 Comment

It depends on your input String no? This is no validation of the input of course. But this was not the question.
1

Building off Torsten's answer, you will probably also want to validate that it is a number.

if(Number(quantity) > 500 || isNaN(quantity)) {

Comments

0

Since you are dealing with numbers, you can get away by using simpler approach. Just validate that it is all digits, and the numeric value is less than or equal to 500

function checkLimit(val){
    if (!isNaN(val) && parseInt(val)<500)
        return true;
    else if(isNaN(val)){
        alert ("Enter valid quantity.");

    return false;
}

if (!checkLimit(quantity))
    alertmsg = alertmsg + "Please limit each magazine to 500 copies or less:" + "\n";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.