gpt4 book ai didi

asp.net-mvc-3 - 使用.SetValidator()时,FluentValidation.Net不会产生客户端非侵入式验证

转载 作者:行者123 更新时间:2023-12-04 02:24:15 25 4
gpt4 key购买 nike

我正在尝试使客户端验证适用于使用编辑器模板的页面。

我的 View 模型的简化示例是:

[Validator(typeof(ValidationTestModelValidator))]
public class ValidationTestModel
{
public string Name { get; set; }

public string Age { get; set; }

public ChildModel Child { get; set; }
}

子模型例如:
public class ChildModel
{
public string ChildName { get; set; }

public string ChildAge { get; set; }
}

我的验证人是:
public class ValidationTestModelValidator : AbstractValidator<ValidationTestModel>
{
public ValidationTestModelValidator()
{
RuleFor(m => m.Name)
.NotEmpty()
.WithMessage("Please enter the name");

RuleFor(m => m.Age)
.NotEmpty()
.WithMessage("Please enter the age");

RuleFor(m => m.Age)
.Matches(@"\d*")
.WithMessage("Must be a number");

RuleFor(m => m.Child)
.SetValidator(new ChildModelValidator());
}
}

子模型验证器例如:
public class ChildModelValidator : AbstractValidator<ChildModel>
{
public ChildModelValidator()
{
RuleFor(m => m.ChildName)
.NotEmpty()
.WithMessage("Please enter the name");

RuleFor(m => m.ChildAge)
.NotEmpty()
.WithMessage("Please enter the age");

RuleFor(m => m.ChildAge)
.Matches(@"\d*")
.WithMessage("Must be a number");
}
}

我已通过将以下内容添加到Application_Start()向MVC3注册了FluentValidation.Net:
// Register FluentValidation.Net
FluentValidationModelValidatorProvider.Configure();

这会完美地为两个属性Name和Age生成毫不干扰的客户端验证,但对于ChildModel上的属性则什么也不会产生。

有什么想法我在这里做错了吗?

更新:如果我仅使用Validator属性注释ChildModel似乎可以正常工作,但是我想有条件地应用验证,因此使用SetValidator()。

最佳答案

我试图分析文档http://fluentvalidation.codeplex.com/wikipage?title=mvc&referringTitle=Documentation。它声明MVC集成默认情况下基于属性工作,因为其验证器工厂使用该属性来实例化适当的验证器。显然,它确实验证了主模型上的属性所引用的ChildModel,但这也许仅仅是对模型结构的自动递归遍历,以生成客户端验证代码。因此,它可能使用相同的机制来为ChildModel类型找到合适的验证器。您能否测试一下,如果删除SetValidator规则(但将属性保留为ChildModel)会发生什么,它是否仍会基于该属性生成验证器?

客户端上有明确支持的验证器列表,但是不幸的是,那里没有提到(或解释过)SetValidator,这是一个不好的信号。

该文档还指出,客户端不支持使用条件的规则,因此很可能您无法使用SetValidator(如您在更新中所述)解决此问题。

另请参阅有关客户端条件规则的讨论:http://fluentvalidation.codeplex.com/discussions/393596。当时的建议是使用jQuery Validation在JS中实现条件规则,但是,如果您需要添加有条件的复杂验证,则可能会很复杂。

如何让它添加带有属性的验证器,但之后又以某种方式抑制它们呢?例如。通过从元素中删除不引人注目的属性?

关于asp.net-mvc-3 - 使用.SetValidator()时,FluentValidation.Net不会产生客户端非侵入式验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9078534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com