FLuentValidation 中未显示 Nullable 类型的错误消息
我在流畅验证方面遇到问题。
我想检查验证,因此该属性的填充值必须大于另一个属性。 这是代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
(我在 FV 论坛 上发布了相同的答案)
该消息不会显示,因为它认为它与错误的属性相关联。当您使用 RuleFor(x => x.MonthlySalesGross.Value) 时,它将规则与名为“Value”的属性关联,而不是与 MonthlySalesGross 属性关联。
FluentValidation v3 增加了对可空值的更好支持(我在博客中介绍了这个 此处),但目前这只适用于常量值,不适用于引用其他属性的表达式。我计划扩展可为空的支持,以便与 v3.1 的跨属性验证器一起使用,但现在您可以通过手动覆盖属性名称来解决此问题。这会将错误与正确的属性重新关联:(
请注意,您还必须在 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:
(note that you also have to include a null check with a When clause).