validate required字段取决于模型MVC中的其他字段

时间:2015-10-21 18:22:28

标签: asp.net-mvc validation model

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

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

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

4 个答案:

答案 0 :(得分:3)

您可以实现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

答案 1 :(得分:3)

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

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

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

Package 而且,对于您的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; }
}

答案 2 :(得分:2)

您可以使用两种选项。

第一个是由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);

答案 3 :(得分:0)

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;
    }