eqiz
eqiz

Reputation: 1591

ASP.Net RegularExpressionValidator Currency Require 2 decimals for validation

I have a very standard ASP.NET RegularExpressionValidator and I just need the ValidationExpression to make it so 2 decimal places are required!

Good Examples..

234234.00
2342342.12
234.11
2.22
3.33

Bad Examples

3242.1
2342
3.1
.22

I tried /^\d{0,4}(\.\d{0,2})?$/ and I can't get it to work.

Upvotes: 4

Views: 3338

Answers (4)

gpersell
gpersell

Reputation: 84

You can set the RegEx value of the validator to the following verbatim string in your server-side code:

@"^\d+\.\d{2}$"

Upvotes: 0

mayo
mayo

Reputation: 4075

Try this:

/\d+\.\d{2}$/

One or more digits, followed by a single dot and followed just for two other digits at the end of the string.

https://regex101.com/r/lF9uU2/1

Upvotes: 1

Osama Aftab
Osama Aftab

Reputation: 1181

Please try this

/^[0-9]+\.?[2]*$/

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626927

You can use

^[0-9]+[.][0-9]{2}$

See regex demo

Regex breakdown:

  • ^ - start of string
  • [0-9]+ - 1 or more digits
  • [.] - a literal .
  • [0-9]{2} - exactly 2 digits
  • $ - end of string.

Your regex - ^\d{0,4}(\.\d{0,2})?$ - matches 0 to 4 digits at the beginning, and then optionally there can be a period followed by 0 to 2 digits before the end of string. It looks like a live validation regex to me, but it cannot be used for final validation.

Upvotes: 4

Related Questions