0

In my ViewModel, I have the following System.ComponentModel.DataAnnotations on a property that contains USD currency:

[DisplayFormat(DataFormatString = "{0:C2}")]
[Range(0.01, 100000, ErrorMessage = "Payment amount is required between .01 and $100,000.")]
[DataType(DataType.Currency)]
[DisplayName("Payment Amount")]
public Double PrinAmount { get; set; } = 0.00;

When I enter a value of $10.005, I get the following validation model error from the ModelState.IsValid check:

The value '$10.005' is not valid for Payment Amount.

When I enter a value 10.005, the ModelState.IsValid is equal to true.

What do I need to do to modified the validation to capture both formats as invalid?

Michael Kniskern
  • 24,792
  • 68
  • 164
  • 231
  • This has already been answered: https://stackoverflow.com/questions/29975128/asp-net-mvc-data-annotation-for-currency-format – Kyle Sep 09 '19 at 21:25
  • Possible duplicate of [ASP.NET MVC data annotation for currency format](https://stackoverflow.com/questions/29975128/asp-net-mvc-data-annotation-for-currency-format) – Kyle Sep 09 '19 at 21:26
  • @Kyle - Do you think my issue is because the property is a data type of `double` instead of a `decimal`? – Michael Kniskern Sep 09 '19 at 21:32
  • Correct, you should not use double for money, but rather decimal. – Kyle Sep 09 '19 at 21:36
  • @Kyle - For the short term, I am going to use the solution provided by ilkerkaran because going down the route of changing the data type will cause a lot more work than just using the regular expression data annotation – Michael Kniskern Sep 09 '19 at 21:56

1 Answers1

1

You can use Regular Expression;

[RegularExpression(@"^\d+\.\d{0,2}$")]

the DataAnnotations above ensures 2 digits.

ilkerkaran
  • 4,214
  • 3
  • 27
  • 42