2016-08-31 69 views
0

在我们当前的catel应用程序中,我们有一个ModelBase类,该类具有另一个ModelBase的成员。(流利)在包含子模型的模型中进行验证

我们希望使用fluentvalidation扩展来为这两种模型编写我们的验证规则。

例如 型号:

public class Model : ModelBase 
{ 
    public Model() 
    { 
     ChildModel = new ChildModel(); 
    } 

    public string FirstName 
    { 
     get { return GetValue<string>(FirstNameProperty); } 
     set { SetValue(FirstNameProperty, value); } 
    } 

    public static readonly PropertyData FirstNameProperty = RegisterProperty("FirstName", typeof(string), string.Empty); 

    public ChildModel ChildModel 
    { 
     get { return GetValue<ChildModel>(ChildModelProperty); } 
     set { SetValue(ChildModelProperty, value); } 
    } 

    public static readonly PropertyData ChildModelProperty = RegisterProperty("ChildModel", typeof(ChildModel), null); 
} 

public class ChildModel : ModelBase 
{ 
    public static readonly PropertyData TestStringProperty = RegisterProperty("TestString", typeof(string), null); 

    public string TestString 
    { 
     get { return GetValue<string>(TestStringProperty); } 
     set { SetValue(TestStringProperty, value); } 
    } 
} 

校验:

public class PersonValidator : AbstractValidator<ModelWithoutValidation> 
{ 
    public PersonValidator() 
    { 
     RuleFor(model => model.FirstName) 
      .NotNull() 
      .NotEmpty(); 

     RuleFor(model => model.MiddleName) 
      .NotNull() 
      .NotEmpty(); 

     RuleFor(model => model.LastName) 
      .NotNull() 
      .NotEmpty() 
      .WithMessage("Last name cannot be empty"); 

     //this doesnt work, so we use a second validator for the ChildModel 
     //RuleFor(model => model.ChildModel.TestString) 
     // .NotNull() 
     // .Length(2, 10) 
     // .When(model => model.ChildModel != null); 
    } 
} 

public class ChildValidator : AbstractValidator<ChildModel> 
{ 
    public ChildValidator() 
    { 
     RuleFor(model => model.TestString) 
      .NotNull() 
      .NotEmpty() 
      .Length(2, 10); 
    } 
} 

父模型只应是有效的,如果所有的子模型是有效的也是如此,有没有办法做到这一点?

而且,即使绑定到子模型属性(TestString)的控件显示存在错误,InfoBarMessageControl也只会显示父控件中父属性的错误。

InfoBarMessageControlFault

它更新表明,有是子模型的变化属性后,一个错误。

回答

1

在父项上,您应该循环您的子模型并手动验证它们。 Catel没有办法自动进行分层验证,并通过IDataErrorInfo界面公开。

您可以创建一个IValidationContext对象,虽然它包含单个上下文中的所有验证。