FluentValidation rule for multiple properties

前端 未结 4 1329
难免孤独
难免孤独 2021-01-01 08:26

I have a FluentValidator that has multiple properties like zip and county etc. I want to create a rule that takes two properties just like a RuleFor construct



        
4条回答
  •  被撕碎了的回忆
    2021-01-01 09:02

    In my case I needed to mark a property as required (x.RequiredProperty in the example below) if another property was not null (x.ParentProperty in the example below). I ended up using the When syntax:

    RuleFor(x => x.RequiredProperty).NotEmpty().When(x => x.ParentProperty != null);
    

    Or if you have more then one rule for a common when clause you can write it as follows:

    When(x => x.ParentProperty != null, () =>
    {
        RuleFor(x => x.RequiredProperty).NotEmpty();
        RuleFor(x => x.OtherRequiredProperty).NotEmpty();
    });
    

    The definition of the When syntax is the following:

    /// 
    /// Defines a condition that applies to several rules
    /// 
    /// The condition that should apply to multiple rules
    /// Action that encapsulates the rules.
    /// 
    public IConditionBuilder When (Func predicate, Action action);
    

提交回复
热议问题