我正在尝试在fluent validation库中使用动态消息构建自定义验证。
例如:
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;
}
}这里有什么解决方法可以通过验证结果吗?
谢谢
发布于 2013-04-09 22:23:00
你试过这样的东西吗?
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,您可以将默认验证消息封装在该类中,并使其成为动态消息。但是,在声明RuleFor时不能使用.WithMessage扩展,因为这会覆盖直接在PropertyValidator中定制的默认验证消息。
发布于 2013-04-09 21:31:34
没有办法做到这一点。我会将您当前拥有的复杂验证方法拆分成较小的方法(IsProcessFileValid1、IsProcessFileValid2、IsProcessFileValid3等)。这样您就可以对错误消息进行更细粒度的控制。此外,每个方法只负责验证一次关注点,使它们更具可重用性(单一责任):
RuleFor(x => x.ProcessFile)
.Must(IsProcessFileValid1)
.WithMessage("Message 1")
.Must(IsProcessFileValid2)
.WithMessage("Message 2")
.Must(IsProcessFileValid3)
.WithMessage("Message 3");还要注意我是如何简化lambda的,因为该方法可以直接作为参数传递给Must。
发布于 2020-03-18 04:42:52
下面是我解决这个问题的方法。使用FluentValidation v8.5.0进行测试
class EmptyValidationMessage : IStringSource
{
public string ResourceName => null;
public Type ResourceType => null;
public string GetString(IValidationContext context)
{
return string.Empty;
}
public static readonly EmptyValidationMessage Instance = new EmptyValidationMessage();
}
public class MyPropValidator : PropertyValidator
{
public MyPropValidator() : base(EmptyValidationMessage.Instance)
{
}
protected override bool IsValid(PropertyValidatorContext context)
{
// if not valid
Options.ErrorMessageSource = new StaticStringSource("my message");
// you can do LanguageStringSource, LazyStringSource, LocalizedStringSource, etc
// example with localized string (https://github.com/clearwaterstream/LocalizedString.FluentValidation)
Options.ErrorMessageSource = new LocalizedStringSource("my message").InFrench("moi message");
return false;
}
}https://stackoverflow.com/questions/15903152
复制相似问题