Using FluentValidation's WithMessage method with a list of named parameters

后端 未结 5 636
长发绾君心
长发绾君心 2021-02-07 04:57

I am using FluentValidation and I want to format a message with some of the object\'s properties value. The problem is I have very little experience with expressions and delegat

5条回答
  •  既然无缘
    2021-02-07 05:40

    Extension methods based on ErikE's answer.

    public static class RuleBuilderOptionsExtensions
    {
        public static IRuleBuilderOptions WithMessage(this IRuleBuilderOptions rule, Func func)
            => DefaultValidatorOptions.WithMessage(rule, "{0}", func);
        public static IRuleBuilderOptions WithMessage(this IRuleBuilderOptions rule, Func func)
            => DefaultValidatorOptions.WithMessage(rule, "{0}", func);
    }
    

    Usage examples:

    RuleFor(_ => _.Name).NotEmpty()
    .WithMessage(_ => $"The name {_.Name} is not valid for Id {_.Id}.");
    
    RuleFor(_ => _.Value).GreaterThan(0)
    .WithMessage((_, p) => $"The value {p} is not valid for Id {_.Id}.");
    

提交回复
热议问题