Moon
Moon

Reputation: 890

Regex Conditional validation

I have a input field, and I want to create a regex that only receive input value from 0.00 to 100.00(include both). I have created a regex check:

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

But with this one, it not only accept values from 0.00 to 100.00 but also accept the input from 100.01 to 199.99.

How can I set a condition that if there are three digital before the dot, it can be only 100 and the decimals part is 00 or 0 only if having decimals?

So 100.00, 100.0 or 100 are the only accept for the values over 99.99 and the input between 100.01 to 199.99 is not pass.

Here are some passed input:

100
100.00
100.0
3
0
0.00
5.2
8.21
37.23

Here are some not passed:

40.323
100.50
101.50
199.99
40.
100.

Upvotes: 0

Views: 76

Answers (3)

Bohemian
Bohemian

Reputation: 425033

Try this:

^(100(\.00?)?|\d\d?)(\.\d\d?)?$

See live demo.

Regex:

  • ^ = start
  • (100|\d\d?) = literal 100 or 1 or 2 digits
  • (\.\d\d?)? = dot then 1 or 2 digits, all optional
  • $ = end

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163362

You can match 0 - 99 with 1 or 2 optional decimals or 100 with optional .0 or .00

^(?:\d\d?(?:\.\d\d?)?|100(?:\.00?)?)$

The pattern in parts:

  • ^ Start of string
  • (?: Non capture group
    • \d\d? Match 1-2 digits
    • (?:\.\d\d?)? Optionally match . and 1-2 digits
    • | or
    • 100(?:\.00?)? Match 100 or 100.0 or 100.00
  • ) Close non capture group
  • $ End of string

Regex demo

Upvotes: 0

NullVoid
NullVoid

Reputation: 847

This should work:

^((?:100(?:\.00?)?)|(?:\d\d?(?:\.\d\d?)?))$

It matches:

  • x
  • x.x
  • x.xx
  • xx
  • xx.x
  • xx.xx
  • 100
  • 100.0
  • 100.00

You can get the match via directly match or with the first capturing group :)

P.S. BTW, @Ouroborus's solution (in comments) also works, and his solution unexpectedly having the exact same length as mine lol:

^(?=.)(100(\.0{1,2})?|\d{1,2}(\.\d{1,2})?)$

Upvotes: 0

Related Questions