4

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
eqiz
  • 1,521
  • 5
  • 29
  • 51

4 Answers4

4

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    works... i'm glad you can make it look so simple lol. Things i read talked about using "d" im not sure why though – eqiz Oct 21 '15 at 22:22
  • There is always a problem with escaping regex metacharacters. Using character classes (those `[...]`) relieves that pain in many cases. – Wiktor Stribiżew Oct 21 '15 at 22:23
  • I see that there are already 2 answers here that look identical to mine. `^\d+\.\d{2}$` is the same as `^[0-9]+[.][0-9]{2}$` in JavaScript ES5 - BUT not in .NET, where `\d` may match Persian and some other numeric characters. Perhaps, you would like to avoid that. Check [this SO answer](http://stackoverflow.com/a/16621778/3832970). – Wiktor Stribiżew Oct 21 '15 at 22:51
1

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

mayo
  • 3,845
  • 1
  • 32
  • 42
0

Please try this

/^[0-9]+\.?[2]*$/
Osama Aftab
  • 1,161
  • 9
  • 15
  • This regex matches 1 or more digits from the beginning of the string, then 1 or 0 dots, and then 0 or more `2` symbols up to the end. I doubt it is what OP needs. – Wiktor Stribiżew Oct 21 '15 at 22:56
0

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

@"^\d+\.\d{2}$"
gpersell
  • 84
  • 1
  • 10