FluentValidation涉及要验证的对象中的2个属性

Sup*_*JMN 1 .net c# fluentvalidation

我有一条业务规则说PropertyA应该是的倍数PropertyB

如您所见,验证并不能单独处理一个属性,而是需要验证两个相互关联的属性。如何使用FluentValidations做到这一点

谢谢!

Sam*_*rie 6

假设您有一个这样的对象:

class Data {
  public int PropertyA;
  public int PropertyB;
}
Run Code Online (Sandbox Code Playgroud)

然后,在验证器中,您可以执行以下操作:

public class DataValidator : AbstractValidator<Data> {

  public DataValidator() {
    // 'x' in this case is the instance of the 'Data' class being validated
    //
    RuleFor(x => x).Must(HaveMultiplierRelationship);
  }

  private bool HaveMultiplierRelationship(Data d)
  {
    return (d.PropertyA % d.PropertyB) == 0;
  }
}
Run Code Online (Sandbox Code Playgroud)

此方法之所以有效,是因为您可以将多个Must调用链接在一起以测试所讨论对象的多个不同方面。

  • 是的,FluentValidation是一个非常漂亮的库。 (2认同)