FlexMcMurphy
FlexMcMurphy

Reputation: 495

Javascript regular expression to match number Zero OR any whole number greater than zero

I have searched for hours but can't find this, please help. I need a Javascript regular expression to validate a text field that will contain a quantity value. The value can be zero OR any whole number greater than zero. Numbers cannot start with a zero unless they are... zero. It should not match if there is any whitespace at the start, middle or end of the quantity "string".

In other words: "0" <- Should match. "467" <- Should match. "098" <- Should not match. "1 3" <- Should not match.

So far I have to use two Reg Exps and OR them in Javascript. It is working. Here is my code:

function qtyIsValid(strQty){
    var isValid;
    var reg1 = new RegExp('^0{1}$'); // <-- This matches a single ZERO and fails if any whitespace anywhere
    var reg2 = new RegExp('^[1-9]+$'); // <-- This matches any number greater than zero and fails if any whitespace anywhere

    if ( reg1.test(strQty) || reg2.test(strQty) ){
            isValid = true;
    }else{
            isValid = false;
        }
return isValid;  
}

But can those two Regular Expressions be combined in to one within Javascript?

Thank you.

Upvotes: 2

Views: 4971

Answers (2)

ibrahim mahrir
ibrahim mahrir

Reputation: 31682

/^(0+|[1-9]\d*)$/ any string that is just a sequence of 0 or that contain a number not equal to 0 and not starting with 0.

console.log("0: ", /^(0+|[1-9]\d*)$/.test("0"));
console.log("000: ", /^(0+|[1-9]\d*)$/.test("000"));
console.log("055: ", /^(0+|[1-9]\d*)$/.test("055"));
console.log("123: ", /^(0+|[1-9]\d*)$/.test("123"));
console.log("1 3: ", /^(0+|[1-9]\d*)$/.test("1 3"));

Upvotes: 1

Dekel
Dekel

Reputation: 62536

You can use this for example:

r = /^(0|[1-9]\d*)$/
console.log("0".match(r));
console.log("467".match(r));
console.log("098".match(r));
console.log("1 3".match(r));

Upvotes: 4

Related Questions