我正在尝试让客户端验证适用于使用编辑器模板的页面。
我的视图模型的简化示例是:
[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()。