Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate decimal value to 2 decimal places with data annotations?

Tags:

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?

like image 892
Steven Avatar asked Mar 04 '12 20:03

Steven


People also ask

How do you validate decimal numbers?

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.

How do you display upto 2 decimal places?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.

How do you print a float value up to 2 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.


2 Answers

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

like image 182
jlew Avatar answered Sep 21 '22 18:09

jlew


[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.

like image 36
Jonathan Avatar answered Sep 17 '22 18:09

Jonathan