【问题标题】:FluentValidation that involves 2 properties in the object being validatedFluentValidation 涉及正在验证的对象中的 2 个属性
【发布时间】:2017-11-07 16:24:28
【问题描述】:

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

如您所见,验证并不仅仅处理一个属性,而是需要验证 2 个相互关联的属性。如何使用 FluentValidations 进行此操作?

【问题讨论】:

    标签: c# .net fluentvalidation


    【解决方案1】:

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

    class Data {
      public int PropertyA;
      public int PropertyB;
    }
    

    然后在验证器中你可以这样做:

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

    此方法效果很好,因为您可以将多个 Must 调用链接在一起以测试相关对象的多个不同方面。

    【讨论】:

    • 看起来真的很优雅。谢谢!
    • 是的,FluentValidation 是一个非常漂亮的库。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    相关资源
    最近更新 更多