验证所需字段取决于模型 MVC 中的其他字段

Mil*_*ind 1 validation asp.net-mvc model

我想创建模型来验证模型中依赖于其他字段条件的所需字段。

public class FixedDeposit
{
   public int DebitAmount { get; set; }
   public string PAN { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

现在,如果 DebitAmount 大于 50,000,则必须需要 PAN 字段。

Ste*_*ene 5

你可以实现 IValidatableObject

public class FixedDeposit : IValidatableObject
{
   public int DebitAmount { get; set; }
   public string PAN { get; set; }

   public IEnumerable<ValidationResult> Validate(ValidationContext   validationContext)
   {
      if (DebitAmount > 50000 && string.IsNullOrEmpty(PAN))
      {
        yield return new ValidationResult("PAN required for debits > 50,000.", new [] { "PAN" } );
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

http://weblogs.asp.net/scottgu/class-level-model-validation-with-ef-code-first-and-asp-net-mvc-3