动态消息流利的验证 [英] Fluent validation with dynamic message
问题描述
我试图构建自定义验证用流利的验证库的动态消息。
I am trying to building custom validation with dynamic message in fluent validation library.
例如:
public class CreateProcessValidator : AbstractValidator<CreateProcessVM>
{
public CreateProcessValidator()
{
RuleFor(x => x.ProcessFile).Must((x,e) => IsProcessFileValid(x.ProcessFile))).WithMessage("Parse failed with error : {0}");
}
public bool IsProcessFileValid(HttpPostedFileBase file)
{
var errorMessage = "..." // pass result to validaton message ?
// logic
return false;
}
}
是这里的任何解决办法如何通过验证的结果?
Is here any workaround how to pass validation result ?
感谢
推荐答案
你有没有尝试过这样的事情?
Have you tried something like this?
public class IsProcessFileValid : PropertyValidator
{
public IsProcessFileValid(): base("{ValidationMessage}") {}
protected override IsValid(PropertyValidatorContext context)
{
if (!IsProcessFileValid1(context))
context.MessageFormatter.AppendArgument("ValidationMessage",
"Custom validation message #1");
if (!IsProcessFileValid2(context))
context.MessageFormatter.AppendArgument("ValidationMessage",
"Custom validation message #2");
// ...etc
return true;
}
private bool IsProcessFileValid1(PropertyValidatorContext context)
{
// logic
return false;
}
private bool IsProcessFileValid2(PropertyValidatorContext context)
{
// logic
return false;
}
// ...etc
}
通过扩展方法:
public static class IsProcessFileValidExtensions
{
public static IRuleBuilderOptions<T, object> MustBeValidProcessFile<T>
(this IRuleBuilder<T, object> ruleBuilder)
{
return ruleBuilder.SetValidator(new IsProcessFileValid());
}
}
...然后使用没有自定义的 WithMessage
:
public CreateProcessValidator()
{
RuleFor(x => x.ProcessFile).MustBeValidProcessFile();
}
通过创建一个自定义的 PropertyValidator
,您可以在类中封装默认的验证消息,并使其充满活力。但是声明,当你不能使用 .WithMessage
延长 RuleFor
,因为这将覆盖默认验证消息,你直接在定制 PropertyValidator
。
By creating a custom PropertyValidator
, you can encapsulate the default validation message within that class and make it dynamic. However you must not use the .WithMessage
extension when declaring the RuleFor
, because that would override the default validation message which you customized directly inside the PropertyValidator
.
这篇关于动态消息流利的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!