Darthg8r
Darthg8r

Reputation: 12675

Number validate regex

From jquery.validate.js, this regex is used to validate a number. The problem is that it fails on .33 and passes on 0.33. I need to make it pass with, or without, the leading 0.

^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$

Upvotes: 3

Views: 222

Answers (4)

davidXYZ
davidXYZ

Reputation: 729

This may be late but I have a better answer. Try this:

^-?((\d+)|([1-9]\d{0,2}(,\d{3})+)|(?=\.))(\.\d+)?$

Both the solutions by refp and solendil above will accept a number like 0,123,456 or 000,123 as valid. These are obviously not valid numbers.

This solution makes sure that the part before the first comma starts with a non-zero digit. It also takes care of the empty string issue that refp pointed out.

Upvotes: 0

kennebec
kennebec

Reputation: 104760

There are simpler ways to tell if a string refers to a number-

function isNumber(str){
    return parseFloat(str)=== Number(str);
}

Upvotes: 1

Filip Roséen
Filip Roséen

Reputation: 63797

A positive lookahead such as (?=[.]) can be used to ensure that the strings either starts with a dot (.) or follow the previously defined pattern.

^-?(?:(?=[.])|\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$

Upvotes: 2

solendil
solendil

Reputation: 8468

Try this

^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$

The extra question mark (spot it!) will make all the part before the decimal point optional.

Upvotes: 4

Related Questions