c# - 如何在 Fluent Validation 中为 Multiple RuleFor 设置单个消息
问题描述
我是流利验证的新手。我有 4 个 if 条件,其中只有一个会执行,我想对这些条件使用 RuleFor。如果条件失败,则应显示错误代码和消息。对于我的 4 个条件,只有一个错误代码和错误消息。
如何在 RuleFor() 中使用 4 个条件以及单个 ErrorCode() 和 WithMessage()
解决方案
WithErrorCode() 和 WithMessage() 接受字符串,因此您只需使用适用的详细信息设置简单的字符串变量并传递变量。
string myerror = "666";
string mymessage = "My Custom message";
RuleFor(person => myclass.Property1).NotNull().WithErrorCode(myerror).WithMessage(mymessage);
RuleFor(person => myclass.Property2).NotNull().WithErrorCode(myerror).WithMessage(mymessage);
RuleFor(person => myclass.Property3).NotNull().WithErrorCode(myerror).WithMessage(mymessage);
RuleFor(person => myclass.Property4).NotNull().WithErrorCode(myerror).WithMessage(mymessage);
您应该考虑这是否有意义,但是验证的目的是增强对数据问题的调试,因此消息和错误代码应尽可能具体。在您的情况下这可能没问题,只有您可以判断。
编辑:在下面回答您的问题。
Fluent Validation 提供了另外两种可能有用的方法。
- 依赖项(参见文档https://docs.fluentvalidation.net/en/latest/conditions.html#dependent-rules)
- CascasdeMode(参见文档https://docs.fluentvalidation.net/en/latest/conditions.html#setting-the-cascade-mode)
我认为依赖项更多的是您正在寻找的。那么你可以有这样的东西;
RuleFor(person => myclass.Property1).NotNull().DependentRules(() => {
RuleFor(person => myclass.Property2).NotNull().WithErrorCode(myerror).WithMessage(mymessage);
RuleFor(person => myclass.Property3).NotNull().WithErrorCode(myerror).WithMessage(mymessage);
RuleFor(person => myclass.Property4).NotNull().WithErrorCode(myerror).WithMessage(mymessage);
}).WithErrorCode(myerror).WithMessage(mymessage);
并且您可以在规则中嵌入规则,使用规则等。但这很快就会变得难以阅读并且难以调试。
推荐阅读
- java - onCreate() 中的 scrollToPosition() 不起作用
- css - 添加变换属性(比例)而不更改先前的变换属性(translate3d)
- angular - Spring RedirectAttributes 不适用于 @PostMapping(value = { "/", "/{id}" })
- javascript - PIXI 在场景中无休止地移动精灵(在顶部显示和在底部隐藏)
- php - 在更新期间测试值
- javascript - 在 JavaScript 中打印之前取消选中 PDF 中的所有单选按钮
- c++ - 在开发 C++ 中编译 sdl 简单程序显示对“WinMain”的未定义引用
- go - 如何为 protbuf 使用自描述消息
- ios - 为什么继承的类不能是json编码
- python - 如何正确重塑张量?