I have this in my view model:
[Required(ErrorMessage = "Price is required")] [Range(0.01, 999999999, ErrorMessage = "Price must be greater than 0.00")] [DisplayName("Price ($)")] public decimal Price { get; set; }
I'd like to validate that the user doesn't enter more than 2 decimal places. So I'd like to have
Valid values: 12, 12.3, 12.34
Invalid values: 12., 12.345
Is there a way to validate this with a data annotation?
It is compulsory to have a dot ('. ') in a text for a decimal value. Minus is used as a decimal number and can be a signed number also. Sign decimal numbers, like -2.3, -0.3 can have minus sign at first position only.
Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.
we now see that the format specifier "%. 2f" tells the printf method to print a floating point value (the double, x, in this case) with 2 decimal places. Similarly, had we used "%. 3f", x would have been printed rounded to 3 decimal places.
You could use the RegularExpression attribute, with a regex that matches your criteria. There are a whole bunch of expressions here that involve numbers, I'm sure one will fit the bill. Here is the link.
This will get you started, though it may not be as inclusive as you want (requires at least one digit leading the decimal point):
[RegularExpression(@"\d+(\.\d{1,2})?", ErrorMessage = "Invalid price")]
Note that it is difficult to emit a precise error message because you don't know which part of the regex failed to match (the string "z.22" has the correct number of decimal places, for example, but is not a valid price).
[RegularExpression(@"^\d+.\d{0,2}$",ErrorMessage = "Price can't have more than 2 decimal places")] public decimal Price { get; set; }
This will cater for 0 to 2 decimal places, or none at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With