2009-02-27 87 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; 
    } 
}