简体   繁体   中英

Enterprise Validation Block different rulsets for parent child classes

Validation on property of child class does not work when I have 2 different rulesets for The parent and child.

This is the class code: Mytype is the parent and Person is the child

    [HasSelfValidation]
    public class MyType
    {
        [SelfValidation(Ruleset = "RulesetA")]
        [SelfValidation(Ruleset = "RulesetB")]
        public void DoValidate(ValidationResults results)
        {
        }

        [NotNullValidator(Ruleset = "RulesetA")]
        [ObjectValidator("RulesetA", Ruleset = "RulesetA")]
        public Person Person { get; set; }

    }

    public class Person
    {
        [NotNullValidator(Ruleset = "RulesetB")]
        public string GivenName { get; set; }

    }

This is the custom validator class to validate MyType class against all rulesets:

    public interface IValidator<T>
    {
        ValidationResults Validate(T target);
    }

    public class MyValidator : IValidator<MyType>
    {
        public ValidationResults Validate(MyType target)
        {
            return Validation.Validate(target, new string[] {"RulesetA", "RulesetB"});
        }
    }

And this is the test which fails: (IsValid should be set to False but it's True)

    [TestMethod]
    public void Should_return_false_when_validating_MyType_without_PersonApplying_GivenName()
    {
        //arrange
        var myType = new MyType()
                            {
                                Person= new Person()
                            };
        myType.Person.GivenName = null;

        //act
        MyValidator _validator = new MyValidator();
        var resultList = _validator.Validate(myType);

        //assert
        Assert.IsFalse(resultList.IsValid);
    }

Would you please help?

VAB validates your object per ruleset and concatenates the validation results. This is what the Validation.Validate method looks like:

var resultsReturned = new ValidationResults();

foreach (string ruleset in rulesets)
{
    var validator = ValidationFactory.CreateValidator(
        targetType, ruleset, source);

    foreach (var validationResult in validator.Validate(target))
    {
        resultsReturned.AddResult(validationResult);
    }
}

return resultsReturned;

In other words, a validation on an object is always performed on a single ruleset. Since the ObjectValidator is only decorated for RulesetA , the Person object will not get validated when running on RulesetB .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM