次のように、インターフェイスを指定し、必要なメソッドIValidatableObject
を定義することで、モデル内の検証をモデル レベルの検証として処理でき ます。Validate()
public class Address : IValidatableObject
{
public int PriceTo { get; set; }
public int PriceFrom { get; set; }
public int CurrencyUnit { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
if(PriceFrom != null && PriceTo != null)
{
if( ! PriceTo > PriceFrom )
{
results.Add (new ValidationResult("\"Price To\" must be greater than \"Price From\"", new List<string> { "PriceTo", "PriceFrom" }));
}
}
if(PriceFrom != null || PriceTo != null)
{
if(CurrencyUnit == null)
{
results.Add (new ValidationResult("If you indicate any prices, you must specify a currency unit"", new List<string> { "CurrencyUnit" }))
}
}
return results;
}
}
注、ただし、MVC クライアント側の検証ではこのルールが適用されるとは思わないため、サーバー側にのみ適用されます。