lynnjwalker
lynnjwalker

Reputation: 761

Pseudo currency regex

I need to validate currency values under $100, allowing the user to optionally leave out the decimal place. The dollar sign and comma are not needed (or allowed). Another validation component constrains the upper and lower values, so the regex expression only needs to validate 1 or 2 digits, with an optional decimal and 2 more digits.

These values would match:

10
5
5.00
10.00

These values would not match:

.25
10.1
10.255

What is the optimal regex pattern for this validation?

Upvotes: 0

Views: 96

Answers (2)

smci
smci

Reputation: 33950

[0-9]{1,2}(\.[0-9]{2}) That should do it.

Upvotes: 1

nu11p01n73R
nu11p01n73R

Reputation: 26667

Something like

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

Regex Demo

  • ^ Anchors the regex at the start of the string

  • d{1,2} matches 1 or 2 digits \d => [0-9]

  • (\.\d{2}) matches . followed by 2 digits

  • ? quantifier, quantifes the decimal part zero or one time

  • $ anchors the regex at the end of the string

Upvotes: 1

Related Questions