加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 使用动态消息进行流畅验证

发布时间:2020-12-16 07:35:56 所属栏目:asp.Net 来源:网络整理
导读:我试图在流畅的验证库中使用动态消息构建自定义验证. 例如 : public class CreateProcessValidator : AbstractValidatorCreateProcessVM{ public CreateProcessValidator() { RuleFor(x = x.ProcessFile).Must((x,e) = IsProcessFileValid(x.ProcessFile)))
我试图在流畅的验证库中使用动态消息构建自定义验证.

例如 :

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;
    }
}

在这里有任何解决方法如何传递验证结果?

谢谢

解决方法

你尝试过这样的事吗?

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中直接自定义的默认验证消息.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读