MVC Validation Lower/Higher than other value

Ben Ford picture Ben Ford · Sep 2, 2013 · Viewed 42k times · Source

How is the best way to validate a model in MVC.Net where I want to accept a minimum/maximum.

Not individual min/max values for a field. But separate fields for a user to specify a minimum/maximum.

public class FinanceModel{
   public int MinimumCost {get;set;}
   public int MaximumCost {get;set;}
}

So I need to ensure that MinimumCost is always less than Maximum cost.

Answer

Matthew picture Matthew · Sep 2, 2013

There is a NuGet package called Foolproof which provides these annotations for you. That said - writing a custom attribute is both pretty easy and good practice.

Using Foolproof would look like:

public class FinanceModel{
   public int MinimumCost {get;set;}

   [GreaterThan("MinimumCost")]
   public int MaximumCost {get;set;}
}