【问题标题】:validate required field depend on other field in model MVC验证必填字段取决于模型 MVC 中的其他字段
【发布时间】:2016-01-20 21:01:56
【问题描述】:

我想创建一个模型,该模型将验证模型中依赖于其他字段条件的必填字段。

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

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

【问题讨论】:

    标签: asp.net-mvc validation model


    【解决方案1】:

    你可以实现 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" } );
          }
       }
    }
    

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

    【讨论】:

    • 这是正确答案,无需向您的应用程序添加额外的包
    【解决方案2】:

    您还可以使用 MVC Foolproof 验证包。这个包以注释的形式为您提供了许多条件验证。

    完整列表在这里: http://foolproof.codeplex.com/

    您可以将此库作为一个包添加到您的 VS 项目中:

    而且,对于您的 FixedPayment 类,它应该如下所示:

    using Foolproof;
    public class FixedDeposit
    {
        public int DebitAmount { get; set; }
    
        [RequiredIf("DebitAmount", Operator.GreaterThan, 50000)]
        public string PAN { get; set; }
    }
    

    备用代码

    using Foolproof;
    public class FixedDeposit
    {
        public int DebitAmount { get; set; }
    
        private bool _panRequired { get { return DebitAmount > 50000; } }
        [RequiredIf("_panRequired", true, ErrorMessage="PAN is required if Debit Amount is greater than 50000")]
        public string PAN { get; set; }
    }
    

    【讨论】:

    • 我已经安装了 MVC Foolproof 验证包。并使用与您提到的相同的语法,但除此之外的所有其他验证都有效。
    • 我用替代实现编辑了我的答案。我在自己的应用中使用了与此替代方案几乎完全相同的东西。
    • 工作正常。谢谢。
    【解决方案3】:

    您可以使用两个选项。

    第一个是 Jaroslaw Waliszko 开发的非常易于使用且相当简洁的ExpressiveAnnotations JS 库。请点击此链接至https://github.com/jwaliszko/ExpressiveAnnotations 了解更多信息。该库允许您执行不同的条件验证。 与Foolproof 类似,它通过添加 NuGet 包添加到您的 Visual Studio 环境中。添加后,在您的模型中添加 using 语句 using ExpressiveAnnotations.Attributes; 然后只需使用 RequiredIf 声明即可完成您需要的操作。例如:

    public class FixedDeposit
    {
       public int DebitAmount { get; set; }
    
       [RequiredIf("DebitAmount >= 50000")]
       public string PAN { get; set; }
    }
    

    第二个选项是使用ModelState.AddModelError()。这是在您的控制器中完成的。只需创建一个新方法:

    private void ValidateRequiredFields(modelname)
    {
        if(modelname.DebitAmount >= 50000)
        {
            if(modelname.PAN == null)
            {
                ModelState.AddModelError("PAN", "Place whatever error message you want here");
            }
        }
    }
    

    接下来,在您希望调用它的任何视图方法中放置对验证方法的引用。引用的行是ValidateRequiredFields(ModelName);

    【讨论】:

      【解决方案4】:
      public class RequiredIfAttribute : RequiredAttribute
      {
          private String PropertyName { get; set; }
          private Object DesiredValue { get; set; }
      
          public RequiredIfAttribute(String propertyName, Object desiredvalue)
          {
              PropertyName = propertyName;
              DesiredValue = desiredvalue;
          }
      
          protected override ValidationResult IsValid(object value, ValidationContext context)
          {
              Object instance = context.ObjectInstance;
              Type type = instance.GetType();
              Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
              if (proprtyvalue.ToString() == DesiredValue.ToString())
              {
                  ValidationResult result = base.IsValid(value, context);
                  return result;
              }
              return ValidationResult.Success;
          }
      }
      

      用法

          [RequiredIf("DebitAmount",50000, ErrorMessage = "PAN field is required")]
          public string PAN
          {get;set;
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-08
        • 2021-09-21
        • 2014-08-17
        • 1970-01-01
        • 2020-02-27
        • 1970-01-01
        相关资源
        最近更新 更多