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?
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):
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).