Search code examples
.netenterprise-library

Help with enterprise library validation results


I'm trying to use Entlib 4's validation blocks but I'm running into a problem clearly identifying invalid properties in the validation results.

In the following example, if the City property fails validation I have no way of knowing whether it was the City property of the HomeAddress object or the WorkAddress object.

Is there a simple way to do this without creating custom validators, etc?

Any insight into what I'm missing or not understanding would be greatly appreciated.

Thank you.

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; }
}

Solution

  • Basically I created a custom validator that extends the ObjectValidator and added a _PropertyName field which gets prepended to the keys of the validationresults.

    So now the usage in the example described above would be:

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

    The validator class:

    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);
            }
        }
    }
    

    And the necessary attribute class:

    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;
        }
    }