【发布时间】:2017-09-17 04:02:19
【问题描述】:
我有以下带有两个构造函数的子验证器,一个没有参数,另一个传递父对象作为参数:
public class ChildValidator : AbstractValidator<Child>
{
public ChildValidator()
{
RuleFor(x => x.LastName)
.NotEmpty()
.WithMessage("Last Name is required");
}
public ChildValidator(Parent parent)
{
RuleFor(x => x.LastName)
.Equal(x => parent.LastName)
.WithMessage("Parent and child Last Name must be equal");
}
}
父验证器:
public class ParentValidator : AbstractValidator<Parent>
{
public ParentValidator()
{
RuleFor(x => x.LastName)
.NotEmpty()
.WithMessage("Last Name is required");
RuleFor(x => x.Children)
.SetCollectionValidator(parent => new ChildValidator(parent));
}
}
型号:
[FluentValidation.Attributes.Validator(typeof(ParentValidator))]
public class Parent
{
public string LastName { get; set; }
public virtual ICollection<Child> Children { get; set; }
}
[FluentValidation.Attributes.Validator(typeof(ChildValidator))]
public class Child
{
public string LastName { get; set; }
public int ParentId { get; set; }
public virtual Parent Parent { get; set; }
}
在子部分视图中:
@using (Html.BeginCollectionItem("Children"))
{
@Html.HiddenFor(model => model.Id)
@Html.HiddenFor(model => model.ParentId)
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
验证工作正常。但是,在显示不带参数的验证器的消息时,不带参数的验证器的消息。
【问题讨论】:
-
孩子与父母的关系如何?一对多?
-
@PateeGutee 一对多。问题已更新。
-
你在哪里设置集合验证器?我知道你说有一个用于 Child 的验证器,但你不是还要在 Parent Validator 中指定 Children 使用 Collection Validator 吗?
-
你也可以添加父验证器吗?
-
@johnny5 问题已更新。
标签: c# asp.net-mvc .net-4.5 fluentvalidation