【发布时间】:2021-04-04 07:15:52
【问题描述】:
我是 Fluent Validation 的新手。我有 4 个 if 条件,其中只有一个会执行,我想对这些条件使用 RuleFor。如果条件失败,应显示错误代码和消息。对于我的 4 个条件,只有一个错误代码和错误消息。
如何在 RuleFor() 中使用 4 个条件以及单个 ErrorCode() 和 WithMessage()
【问题讨论】:
标签: c# .net .net-core fluentvalidation
我是 Fluent Validation 的新手。我有 4 个 if 条件,其中只有一个会执行,我想对这些条件使用 RuleFor。如果条件失败,应显示错误代码和消息。对于我的 4 个条件,只有一个错误代码和错误消息。
如何在 RuleFor() 中使用 4 个条件以及单个 ErrorCode() 和 WithMessage()
【问题讨论】:
标签: c# .net .net-core fluentvalidation
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 提供了另外两种可能有用的方法。
我认为依赖项更符合您的要求。那么你就可以拥有这样的东西了;
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);
您可以在规则中嵌入规则,使用规则等。但这很快就会变得难以阅读并且难以调试。
【讨论】: