简体   繁体   English

FluentValidation:使用来自其他属性的值自定义错误消息

[英]FluentValidation: Customizing the error message with values from other properties

I have this:我有这个:

 RuleForEach(inputData => inputData.Loads).ChildRules(inputData => {
        inputData.RuleFor(load => load.Asnow).GreaterThanOrEqualTo(0).WithMessage("no negative snow allowed"));
.... etc

Now I want to express in the message, which of the loads in the Loads collection the message is about.现在我想在消息中表达消息是关于 Loads 集合中的哪些负载。

"load" has a property "LoadName", the value of which i want to include in the message, something like “load”有一个属性“LoadName”,我想在消息中包含它的值,比如

$"{load.LoadName} no negative snow allowed" 

How can I do that?我怎样才能做到这一点?

Use the WithMessage(Func<T, string>) overload:使用WithMessage(Func<T, string>)重载:

RuleForEach(inputData => inputData.Loads)
    .ChildRules(inputData =>
    {
        inputData.RuleFor(load => load.Asnow).GreaterThanOrEqualTo(0).WithMessage(load => $"{load.LoadName} no negative snow allowed");
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM