繁体   English   中英

跳过基于其属性之一的模型的所有验证(ASP.Net Core 2.0)

[英]Skip all the validation of a model base on one of its property (ASP.Net Core 2.0)

我如何可以跳过基于其属性之一的模型的所有验证。 例如,如果对象的WillBeDeleted属性为 true,验证器将跳过所有验证规则。

namespace ViewModel
{
    public class ContactForm : IViewModel
    {
        [ValidateNever]
        public Contact Item { get; set; }

        public Category Category { get; set; }

        [Required, DisplayName("First name")]
        [StringLength(200, ErrorMessage = "First name should not exceed 200 characters.")]
        public string FirstName { get; set; }

        [Required, DisplayName("Last name")]
        [StringLength(200, ErrorMessage = "Last name should not exceed 200 characters.")]
        public string LastName { get; set; }

        public List<TelephonesSubForm> Telephones { get; set; } = new List<TelephonesSubForm>();

        public List<EmailsSubForm> Emails { get; set; } = new List<EmailsSubForm>();

        public class TelephonesSubForm : IViewModel
        {
            public int Id { get; set; }

            public bool MustBeDeleted { get; set; }

            [Required]
            public TelephoneAndEmailType Type { get; set; }

            [Required]
            [StringLength(200, MinimumLength = 10, ErrorMessage = "Telephone should not exceed 200 characters.")]
            public string Telephone { get; set; }
        }

        public class EmailsSubForm
        {
            public int Id { get; set; }

            public bool MustBeDeleted { get; set; }

            [Required]
            public TelephoneAndEmailType Type { get; set; }

            [Required]
            [StringLength(200, MinimumLength = 10, ErrorMessage = "Email should not exceed 200 characters.")]
            public string Email { get; set; }
        }
    }
}

在给定的示例模型中,当MustBeDeletedtrue ,表示将在保存操作中删除电子邮件或电话项。

我搜索并发现了几个关于条件(自定义)验证的问题,他们建议在检查ModelState的验证状态之前从ModelState删除特定的键。 这个

我正在添加一个新答案并保留旧答案,因为它可能对某人有用

因此,创建一个自定义属性:

  public class CustomShouldValidateAttribute : Attribute, IPropertyValidationFilter
  {
    public CustomShouldValidateAttribute(){

    }
    public bool ShouldValidateEntry(ValidationEntry entry, ValidationEntry parentEntry)
    {
      //Here you change this verification to Wether it should verificate or not, In this case we are checking if the property is ReadOnly (Only a get method)
      return !entry.Metadata.IsReadOnly;      
    }
  }

和他们在你的班级上你用你的自定义属性装饰它

[CustomShouldValidateAttribute]
public class MyClass{
public string Stuff{get;set;}
public string Name {get{return "Furlano";}}
}

尽管这不是问题的完整答案,但可以继承验证属性( RequiredAttributeStringLength )并覆盖IsValid方法。 作为示例,我提供其中之一。

public class RequiredWhenItIsNotDeletingAttribute : RequiredAttribute
{
    string DeletingProperty;

    /// <summary>
    /// Check if the object is going to be deleted skip the validation.
    /// </summary>
    /// <param name="deletingProperty">The boolean property which shows the object will be deleted.</param>
    public RequiredWhenItIsNotDeletingAttribute(string deletingProperty = "MustBeDeleted") =>
        DeletingProperty = deletingProperty;

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var property = validationContext.ObjectType.GetProperty(DeletingProperty);

        if((bool)property.GetValue(validationContext.ObjectInstance))
            return ValidationResult.Success;

        return base.IsValid(value, validationContext);
    }
}

从 IValidatableObject 继承您的模型

并实现接口方法:

  public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {

      if (YourCondition==false){
        yield return new ValidationResult(
          $"This is wrong",
          new[] { nameof(Email) });
      }
      else
         yield return ValidationResult.Success

    }

但是您必须为您的每个属性实现验证并排除您已经编写的装饰!

您可以调用该方法:

ModelState.Clear()

当 MustBeDeleted 为真时

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM