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

后端 未结 5 635
长发绾君心
长发绾君心 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

    With C# 6.0, this is greatly simplified. Now you can just do this (a little bit of a hack, but a lot better than forking Fluent Validation):

    RuleFor(x => x.Name).NotEmpty()
       .WithMessage("{0}", x => $"The name {x.Name} is not valid for Id {x.Id}.");
    

    Pity they didn't offer a WithMessage overload that takes a lambda accepting the object, and you could just do:

    RuleFor(x => x.Name).NotEmpty()
       .WithMessage(x => $"The name {x.Name} is not valid for Id {x.Id}.");
    

    I think it's silly they tried to duplicate string.Format themselves in the goal to achieve shorter syntax, but ultimately made it less flexible so that we can't use the new C# 6.0 syntax cleanly.

提交回复
热议问题