Skip to content

AncestorTypeValidator

crmckenzie edited this page Mar 30, 2012 · 1 revision

This validator returns validation results for the super-type of a given class. In the Personnel sample, Manager inherits Employee. The SaveManagerValidator inherits CompositeValidator. I want to add special validations for the Manager sub-type, and reuse existing validations for Employee. The AncestorTypeValidator will execute Validator.Validate on the manager instance and merge those results with the results from the other validators.

Sample

    public class SaveManagerValidator : CompositeValidator<Manager>
    {
        public override bool AppliesTo(string rulesSet)
        {
            return rulesSet == RulesSets.Crud.Save;
        }

        protected override IEnumerable<IValidator<Manager>> GetInternalValidators()
        {
            yield return Properties<Manager>
                .For(m => m.Reports)
                .Required()
                .Count(minCount:1, maxCount:null)
                .Severity(ValidationResultSeverity.Warning)
                .Message("Manager should have at least 1 report!")
                .Unique(e => e.EmployeeId)
                .Cascade(RulesSets.Crud.Save)
                ;

            yield return new AncestorTypeValidator<Manager, Employee>();
        }
    }