像这样创建一个自定义属性验证器
public class AllChildBirtdaysMustBeLaterThanParent : PropertyValidator
{
public AllChildBirtdaysMustBeLaterThanParent()
: base("Property {PropertyName} contains children born before their parent!")
{
}
protected override bool IsValid(PropertyValidatorContext context)
{
var parent = context.ParentContext.InstanceToValidate as Parent;
var list = context.PropertyValue as IList<Child>;
if (list != null)
{
return ! (list.Any(c => parent.BirthDay > c.BirthDay));
}
return true;
}
}
添加这样的规则
public class ParentValidator : AbstractValidator<Parent>
{
public ParentValidator()
{
RuleFor(model => model.Name).NotEmpty();
RuleFor(model => model.Children)
.SetValidator(new AllChildBirtdaysMustBeLaterThanParent());
// Collection validator
RuleFor(model => model.Children).SetCollectionValidator(new ChildValidator());
}
}
自定义属性验证器的替代方法是使用自定义方法:
public ParentValidator()
{
RuleFor(model => model.Name).NotEmpty();
RuleFor(model => model.Children).SetCollectionValidator(new ChildValidator());
Custom(parent =>
{
if (parent.Children == null)
return null;
return parent.Children.Any(c => parent.BirthDay > c.BirthDay)
? new ValidationFailure("Children", "Child cannot be older than parent.")
: null;
});
}
显示失败指标的粗略方式:(可能应该是其他标识符的名称)
public class ParentValidator : AbstractValidator<Parent>
{
public ParentValidator()
{
RuleFor(m => m.Children).SetCollectionValidator(new ChildValidator());
Custom(parent =>
{
if (parent.Children == null)
return null;
var failIdx = parent.Children.Where(c => parent.BirthDay > c.BirthDay).Select(c => parent.Children.IndexOf(c));
var failList = string.Join(",", failIdx);
return failIdx.Count() > 0
? new ValidationFailure("Children", "Child cannot be older than parent. Fail on indicies " + failList)
: null;
});
}
}