Search code examples
c#asp.net-mvcvalidationdata-annotations

How to validate that a given amount is not greater than some amount using Data annotation validations?


I have a class

Public class Transaction{

[Required]
//[RegularExpression(@"\d{1, 5}\.\d{1,2}", ErrorMessage = "Amount has to be 
positive and upto 2 decimal places")]
[Range(0, 20000, ErrorMessage = "Maximum transaction amount can not exceed 
20000.")]
[RegularExpression(@"^[0-9]*(\.[0-9]{1,2})?$", ErrorMessage = "Amount has to 
be positive and upto 2 decimal places")]
public float Amount { get; set; }

}

I don't want the user to enter an amount greater than 20K and at any point only two decimal places.

I have written above validations, but when I enter a big number like 1453668789564565656. It looks like Range Validation throws an exception "value was either too large or too small for an int32."

Can someone guide me here. How can I make this work?


Solution

  • You need to use the constructor with double parameters, i.e.

    [Range(0.0, 20000.0, ErrorMessage = "Maximum transaction amount can not exceed 20000.")]