Joe
Joe

Reputation: 4542

Regex to validate number between two ranges

how to validate numbers between 0 to 99999.99 using regex?

basically it should accept the values like 0.01, 0000.01, .01 and 9999.99

also it should have only two values after dot(.)

I tried something like the below but it did not work for me.

/^[0-9]{1,5}.[0-9]{2}$/ 

decimal is optional

Could someone help pls.

Upvotes: 0

Views: 547

Answers (4)

Joe
Joe

Reputation: 4542

The regex ^(?:\d{1,5}(?:\.\d{1,2})?|\.\d{1,2})$ is what I was trying to get.

Upvotes: 0

Sanj
Sanj

Reputation: 4029

Javascript regex:

/^\d{1,5}(\.\d{1,2})?$/

Javascript demo

Upvotes: 0

Andreas
Andreas

Reputation: 159215

The . character has special meaning in a regex, so you need to escape it.

Anyway, let me see if I got the rules straight:

  • Decimal point is optional
  • If decimal point not given:
    • Between 1 and 5 digits
  • If decimal point is present:
    • Between 0 and 5 digits before decimal point
    • Between 1 and 2 digits after decimal point

Since the number of digits depends on the presence of the decimal point, you make the regex have two choices, separated by |.

Choice 1 (no decimal point): [0-9]{1,5}

Choice 2 (decimal point): [0-9]{0,5}\.[0-9]{1,2}

Since you want anchors (^$), you can either put them in both choices, or surround the choice set with parenthesis. To make it non-capturing, use (?:xxx).

Final regex is one of these:

/^[0-9]{1,5}$|^[0-9]{0,5}\.[0-9]{1,2}$/
/^(?:[0-9]{1,5}|[0-9]{0,5}\.[0-9]{1,2})$/

You can see the second one in effect on regex101.

Upvotes: 3

Pallav Jha
Pallav Jha

Reputation: 3619

If javascript then below regex would work:

^\d{0,5}(((\.){0})|((\.){1}\d{1,2}))$

All the above mentioned cases are satisfying.

Upvotes: 0

Related Questions