dai.hop
dai.hop

Reputation: 761

Regex - Quantity Field

I want to validate the contents of a quantity field using Javascript's Regular Expressions.

Valid input would be an integer number, from zero upwards. If leading zeros could be removed too that would be great.

Examples

1         Pass
0         Pass
01        Failed
00        Failed
-1        Failed
1.1       Failed
1000000   Pass

I have tried myself, but the best I got was...

var regex = /[0-9]{1,9}/;

...which doesn't fail on negative numbers, or numbers with leading zeros.

Thanks!

Upvotes: 1

Views: 4208

Answers (4)

Roland Bouman
Roland Bouman

Reputation: 31961

var re = /^0*([^0]\d*)$/;
var match = re.exec(str);
if (match) {
    var i = parseInt(match[1], 10);
}
else {
    //whoops, not an integer
}

(match[1] returns the int without leading zeroes, match[0] the entire matched string).

Upvotes: 0

This regular expression matches any sequence of digits without a leading 0 (except for 0 itself, which is handled separately).

var regex = /^0$|^[1-9][0-9]*$/;

^ and $ are anchors, which anchor the match to the beginning and end of the string. This means, nothing is allowed before or after the number, and as such, no minus can be included.

Upvotes: 4

Martin Ender
Martin Ender

Reputation: 44259

If you want to remove leading zeros instead of forbidding them, then you can use this:

^0*(\d{1,9})$

Now you will find the number without trailing zeros in captured group no. 1 (even if only one 0 was entered).

Upvotes: 1

undefined
undefined

Reputation: 2101

Try ^\d+$. Should match positive integers.

Upvotes: 0

Related Questions