Karishma Germanwala
Karishma Germanwala

Reputation: 31

regex for price validation

I am trying to find a regular expression which accepts maximum 5 digits before decimal and maximum 2 digits after decimal. Decimal part is optional and should not accept if 0 is the only digit. But accepts if 0 is followed by other digits after or before decimal. For example:

Valid data are : 12345.12,123.12,0.12,00.12,1.2,0123.12

Invalid data are: 0,00,000,0000,00000

I have made an expression ^\d{0,5}(\.\d{1,2})?$" but this does not work if the digit starts with 0.

Upvotes: 3

Views: 1884

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

empty string is not allowed but values like 00001.01 is valid

You can use the following regex with negative look-aheads that check for disallowed values:

 ^(?!$)(?!0+$)\d{0,5}(?:\.(?!0{1,2}$)\d{1,2})?$
  ^^^^^ ^^^^^              ^^^^^^^^^

See demo

The regex breakdown:

  • ^ - start of string
  • (?!$) - make sure the string is not empty (the end of string does not appear right after the beginning)
  • (?!0+$) - makes sure the integer number does not consist of only zeros
  • \d{0,5} - 0 to 5 digits
  • (?:\.(?!0{1,2}$)\d{1,2})? - an optional sequence of...
    • \. - a decimal period
    • (?!0{1,2}$)\d{1,2} - 2 or 1 digits (\d{1,2}) that is not 0 or 00 ((?!0{1,2}$))
  • $ - end of string

Upvotes: 0

vks
vks

Reputation: 67968

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

 ^^^^^^^

Just add a lookahead which would fail the regex if it finds only 0.

EDIT:

If you dont want to allow 0.0 use

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

Upvotes: 4

w.b
w.b

Reputation: 11228

This also works:

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

(?!(\.|,)0{2}) asserts the number doesn't contain only 0s after decimal point.

Demo on regex101

Upvotes: 0

Related Questions