内部类,负责验证我有简单的规则:FluentValidation修改错误信息
RuleFor(u => u.Id)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty().WithMessage("Id is required")
.Must(ValidateId);
以下是我ValidateId
功能:
private bool ValidateId(CreateAccountBindingModel model, string id, PropertyValidatorContext context)
{
if (id=="test")
{
context.Rule.CurrentValidator.ErrorCodeSource = new StaticStringSource("You are testing");
return false;
}
var idValid = IdValidator.IsValid(id);
if (!idValid)
{
context.Rule.CurrentValidator.ErrorCodeSource = new StaticStringSource("Id is invalid");
return false;
}
return true;
}
如果我跑我的验证,我得到默认错误,而不是我在我的函数中指定的自定义错误。
我试着使用它们设置:
context.Rule.CurrentValidator.ErrorCodeSource = new StaticStringSource("Id is invalid");
,但没有任何运气。
如何在验证功能中定义错误消息?
@ AlekseyL.sorry回复这样的迟到。我创建了扩展名,允许我为每个规则调用'OnFailure'。我已经在FluentValidation repo中发布了我的代码(https://github.com/JeremySkinner/FluentValidation/issues/299#issuecomment-233904267),我正在等待Jeremy的评论。我已经在我的项目中实现了这个解决方案,并且它工作正常,但是我希望在我发布之前获得作者的评论。也许你可以看看它? – Misiu
我认为这与这个问题无关。 –
@AlekseyL。对于那个很抱歉。我错了问题。该链接是相关的http://stackoverflow.com/questions/38436630/fluentvalidation-logonfailure-override – Misiu