简体   繁体   English

如何在流畅的验证中检查其他属性使用自定义规则

[英]How check other property use custom rule in fluent validation

Let's say there is a class and I need to check the value of property 1 against the value of property 2 so that it can be reused.假设有一个 class,我需要检查属性 1 的值与属性 2 的值,以便它可以被重用。 I don't understand how you can pass the value of 2 properties to a custom validation rule of 1 property using fluent validation我不明白如何使用流畅验证将 2 个属性的值传递给 1 个属性的自定义验证规则

I have class我有 class

public class MyClass
{
    public string Property1 { get; set; }  
    public string Property2 {get; set; }     
    public string Property3 { get; set; } 
} 

and validato class和验证 class

public class MyClassValidator : AbstractValidator<MyClass>
{
    public MyClassValidator ()
    {
        RuleFor(мyClass => мyClass.Property1).Property1();
    }
}

and custom rule和自定义规则

public static IRuleBuilderOptions<T, string>
    Property1<T>(this IRuleBuilder<T, string> ruleBuilder)
    {
        return ruleBuilder.NotNull()
                          .NotEmpty()
                          .Length(12)
    }

I want the rule我想要规则

public static IRuleBuilderOptions<T, string>

    Property1<T>(this IRuleBuilder<T, string> ruleBuilder)
    {
        return ruleBuilder.Custom((x, c) => {
        if(x.Property2== "qwerty")
         if(x.Property1=="q")
          context.AddFailure("")
        });
    }

How can i pass property value of Property2 to Property1 property check?如何将 Property2 的属性值传递给 Property1 属性检查?

Edit1 I want this check to be used on other classes Edit1 我希望这张支票用于其他班级

I just want to thank you for your reply.我只是想感谢你的回复。 So I decided not only to look at the answers, but also to ask my first question所以我决定不仅要看答案,还要问我的第一个问题

You need a custom validator .您需要一个自定义验证器 To quote an example from the docs...引用文档中的示例...

public class PersonValidator : AbstractValidator<Person> {
  public PersonValidator() {
   RuleFor(x => x.Pets).Custom((list, context) => {
     if(list.Count > 10) {
       context.AddFailure("The list must contain 10 items or fewer");
     }
   });
  }
}

The context gives you access to the whole object being validated, so you can get at any other properties you want. context使您可以访问正在验证的整个 object,因此您可以获取所需的任何其他属性。

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

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