2009-02-27 84 views
1

我想使用Entlib 4的验证块,但我遇到了一个问题,在验证结果中清楚地标识了无效属性。帮助企业库验证结果

在以下示例中,如果City属性未通过验证,我无法知道它是HomeAddress对象的City属性还是WorkAddress对象。

有没有一种简单的方法来做到这一点,而无需创建自定义验证器等?

任何洞察到我失踪或不理解将不胜感激。

谢谢。

public class Profile 
{ 
    ... 
    [ObjectValidator(Tag = "HomeAddress")] 
    public Address HomeAddress { get; set; } 

    [ObjectValidator(Tag = "WorkAddress")] 
    public Address WorkAddress { get; set; } 
} 
... 
public class Address 
{ 
    ... 
    [StringLengthValidator(1, 10)] 
    public string City { get; set; } 
} 

回答

0
基本上

我创建的延伸ObjectValidator一个定制的验证和向其中加入被前置到validationresults的密钥的_PropertyName字段。

所以现在在上述的例子中的用法是:

public class Profile 
{ 
    ... 
    [SuiteObjectValidator("HomeAddress")] 
    public Address HomeAddress { get; set; } 

    [SuiteObjectValidator("WorkAddress")] 
    public Address WorkAddress { get; set; } 
} 

验证器类:

public class SuiteObjectValidator : ObjectValidator 
{ 
    private readonly string _PropertyName; 

    public SuiteObjectValidator(string propertyName, Type targetType) 
     : base(targetType) 
    { 
     _PropertyName = propertyName; 
    } 

    protected override void DoValidate(object objectToValidate, object currentTarget, string key, 
             ValidationResults validationResults) 
    { 
     var results = new ValidationResults(); 

     base.DoValidate(objectToValidate, currentTarget, key, results); 


     foreach (ValidationResult validationResult in results) 
     { 
      LogValidationResult(validationResults, validationResult.Message, validationResult.Target, 
           _PropertyName + "." + validationResult.Key); 
     } 
    } 
} 

和必要的属性类:

public class SuiteObjectValidatorAttribute : ValidatorAttribute 
{ 
    public SuiteObjectValidatorAttribute() 
    { 
    } 

    public SuiteObjectValidatorAttribute(string propertyName) 
    { 
     PropertyName = propertyName; 
    } 

    public string PropertyName { get; set; } 

    protected override Validator DoCreateValidator(Type targetType) 
    { 
     var validator = new SuiteObjectValidator(PropertyName, targetType); 
     return validator; 
    } 
}