I'm having a problem applying Rulesets when validating objects with nested objects when using Enterpirse Library validation. If I have the following objects
public class Person
{
[ObjectValidator]
[ObjectValidator(Ruleset = "A")]
public Address Address { get; set; }
}
public class Address
{
[StringLengthValidator(0, 32, MessageTemplate = "Invalid value '{0}' for {1}, Max length:{5}")]
public string Address1 { get; set; }
[StringLengthValidator(0, 32, MessageTemplate = "Invalid value '{0}' for {1}, Max length:{5}", Ruleset = "A")]
public string Address2 { get; set; }
}
Now if I try to validate the object by calling
ValidationResults results = Validation.Validate(myPersonObject);
I get my default validation as expected, i.e if Person.Address.Address1 is too long it fires but Person.Address.Address2 is ignored, this is as expected.
However if I try to invoke my validation for Ruleset "A" as follows
ValidationResults results = Validation.Validate(myPersonObject, "A");
I always get the same results as the previous validate call despite the fact I have specified the Ruleset. Any suggestions?
So turns out I need to pass my Ruleset through in the constructor of the ObjectValidator attribute as well as specifying the Ruleset property to get my expected behaviour.
public class Person
{
[ObjectValidator]
[ObjectValidator("A", Ruleset = "A")]
public Address Address { get; set; }
}
public class Address
{
[StringLengthValidator(0, 32, MessageTemplate = "Invalid value '{0}' for {1}, Max length:{5}")]
public string Address1 { get; set; }
[StringLengthValidator(0, 32, MessageTemplate = "Invalid value '{0}' for {1}, Max length:{5}", Ruleset = "A")]
public string Address2 { get; set; }
}
Basically the constructor argument is the target ruleset in the target object ("Address") while the Ruleset named parameter is what the ruleset is called on the current object ("Person").