Search code examples
asp.net-mvcentity-frameworkasp.net-mvc-4entity-framework-5data-annotations

DataAnnotation Range


Hypothetically, I have a points table and you can enter 0 to 10 points at a time. Also you can submit points multiple times, but the sum of your points should never exceed 100. If you have a total of 90 points and you try to enter 11 an error message should say "You have exceeded the maximum". Is this possible to do using DataAnnotations? I have seen the range validator but it seems to only apply per entry not for the sum of items.

How can I validate the sum?


Solution

  • What you want to do is keep the Range attribute, which will serve to cover most scenarios, and then just handle the edge case explicitly:

    [HttpPost]
    public ActionResult AddPoints(int points)
    {
        var currentPoints = repository.GetPointsForUser(User.Identity.Name);
        if (currentPoints + points > 100)
        {
            ModelState.AddModelError("points", string.Format("The points you specified would exceed the maximum of 100, please enter {0} or fewer.", 100 - currentPoints))
        }
    
        if (ModelState.IsValid)
        {
            ...
        }
    }
    

    Now, I took a number of liberties with the above code, because I know nothing about your application, but hopefully, it's generic enough that you can at least get the point.