Validation Application Block. Validate Explicit properties

Topics: Validation Application Block
Feb 21, 2013 at 2:52 PM
Edited Feb 21, 2013 at 2:56 PM
I have some class, which inherits an interface.
[MetadataType(typeof(PersonMetadata))]
class Person : ValidatableItemBase, IPerson
{
    int IPerson.BirthDate { get; set; }
    public DateTime? BirthDate { get; set; }
}

interface IPerson
{
    int BirthDate { get; set; }
}
And I have metadata class with validators
public class PersonMetadata : IPerson
{
    [RangeValidator(...)]
    public int BirthDate { get; set; }
}
The problem is, that validators assigned to int property instanced and tryed to be applyed on a DateTime property, which causes an exception.
Now I found one solution: extend metadata and override target property with all validators, but it's causes need of syncronising validation rules during changes.

Is it possible to make validators validate explicit property?
I'm using Enterprise Library 5.0
Editor
Feb 22, 2013 at 5:35 AM
Edited May 1, 2013 at 9:47 PM
Out of the box for interfaces you would need to put the attribute directly on the interface:
interface IPerson
{
     [RangeValidator(...)]
     int BirthDate { get; set; }
}
And then validate against the IPerson interface as well as also validate against Person:
var validator = ValidationFactory.CreateValidator<IPerson>();
var validationResults = validator.Validate(person);
validationResults.AddAllResults(ValidationFactory.CreateValidator<Person>().Validate(person));
Another similar approach would be to define the validation rules in configuration instead of attributes: one rule for Person and another rule for IPerson and then create Person and IPerson validators and validate the instance against both of those validators.

Self validation might be a good alternative here to perform the interface validation. Except that self validation is not supported along with MetadataTypeAttribute. However, following the approach outlined in Mixing Validation Application Block With DataAnnotation: What About SelfValidation? it might be possible to either write self validation to validate the interface or, since the approach in the article is to create a new AttributeValidatorFactory, generate the appropriate validators that you wish based on the metadata.

~~
Randy Levy
entlib.support@live.com
Enterprise Library support engineer
Support How-to
Marked as answer by randylevy on 10/7/2013 at 11:11 PM
Jul 10, 2013 at 4:12 PM
Thanks a lot! Interface resolves the problem