FLuentValidation 中未显示 Nullable 类型的错误消息

发布于 2024-11-27 00:10:16 字数 524 浏览 0 评论 0原文

我在流畅验证方面遇到问题。

我想检查验证,因此该属性的填充值必须大于另一个属性。 这是代码:

public decimal? MonthlySalesNet { get; set; }
public decimal? MonthlySalesGross { get; set; }

这是验证:

RuleFor(x => x.MonthlySalesGross.Value).GreaterThan(x => x.MonthlySalesNet.Value)
            .When(x => x.MonthlySalesGross != null && x.MonthlySalesNet != null)
            .WithMessage("blahblah");

验证正在工作,但未显示消息。我错过了什么吗?

当我将十进制更改为不可为空类型并重新配置验证时,显示了错误消息验证。这对我来说很奇怪,谢谢

I have problem with Fluent Validation.

I want to check the validation so the property must be filled greater than another property.
here is the code :

public decimal? MonthlySalesNet { get; set; }
public decimal? MonthlySalesGross { get; set; }

and here is the validation :

RuleFor(x => x.MonthlySalesGross.Value).GreaterThan(x => x.MonthlySalesNet.Value)
            .When(x => x.MonthlySalesGross != null && x.MonthlySalesNet != null)
            .WithMessage("blahblah");

the validation was working but the message was not shown. am I missing something?

when I was changed decimal to not nullable type and reconfigure the validation, the error message validation was shown. it`s weird for me,,Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

执笔绘流年 2024-12-04 00:10:16

(我在 FV 论坛 上发布了相同的答案)

该消息不会显示,因为它认为它与错误的属性相关联。当您使用 RuleFor(x => x.MonthlySalesGross.Value) 时,它将规则与名为“Value”的属性关联,而不是与 MonthlySalesGross 属性关联。

FluentValidation v3 增加了对可空值的更好支持(我在博客中介绍了这个 此处),但目前这只适用于常量值,不适用于引用其他属性的表达式。我计划扩展可为空的支持,以便与 v3.1 的跨属性验证器一起使用,但现在您可以通过手动覆盖属性名称来解决此问题。这会将错误与正确的属性重新关联:(

RuleFor(x => x.MonthlySalesGross.Value)
    .GreaterThan(x => x.MonthlySalesNet.Value)
    .When(x => x.MonthlySalesGross.HasValue)
    .OverridePropertyName("MonthlySalesGross");

请注意,您还必须在 When 子句中包含空检查)。

(I posted the same answer over on the FV forum)

The message doesn't display because it thinks it's associated with the wrong property. When you use RuleFor(x => x.MonthlySalesGross.Value), it associates the rule with a property called "Value" rather than with the MonthlySalesGross property.

FluentValidation v3 adds better support for nullables (I blogged about this here), but at present this only works with constant values, not expressions that reference other properties. I'm planning to expand the nullable support to work with cross-property validators with v3.1, but for now you can work around this by manually overriding the property name. This will re-associate the error with the correct property:

RuleFor(x => x.MonthlySalesGross.Value)
    .GreaterThan(x => x.MonthlySalesNet.Value)
    .When(x => x.MonthlySalesGross.HasValue)
    .OverridePropertyName("MonthlySalesGross");

(note that you also have to include a null check with a When clause).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文