views:

60

answers:

1

I am using Rulesets on a type that looks like this:

public class Salary
{

   public decimal HourlyRate { get; set; }

   [ValidHours]  //Custom validator
   public int NumHours { get; set; }

   [VerifyValidState(Ruleset="State")]  //Custom validator with ruleset
   public string State { get; set; }
}

Due to business requirements, I'd need to first validate the ruleset "State" and then validate the entire business entity

public void Save()
{
   ValidationResults results = Validation.Validate(salary, "State");

   //Check for validity

   //Now run the validation for ALL rules including State ruleset
   ValidationResults results2 = Validation.Validate(salary); //Does not run the ruleset marked with "State"

}

How do I accomplish what I am trying to do?

+1  A: 

You will need to add VerifyValidState to both RuleSets:

public class Salary
{

   public decimal HourlyRate { get; set; }

   [ValidHours]  //Custom validator
   public int NumHours { get; set; }

   [VerifyValidState]  
   [VerifyValidState(Ruleset="State")]  //Custom validator with ruleset
   public string State { get; set; }
}

Then you can invoke each RuleSet separately (which you were already doing). The code will look like:

public void Save()
{
    ValidationResults results = Validation.Validate(salary, "State");

    //Check for validity
    if (results.IsValid)
    {    
        //Now run the validation for ALL rules including State ruleset
        results.AddAllResults(Validation.Validate(salary)); 
    }    
}
Tuzo
@Tuzo - Very nice. I will try that. I have a quick unrelated question. If I have my validation rules spread out both in config files and attributes, I understand I can use the IConfigurationSource to read rules from the config file. But, can I combine them with the rules specified as attributes on the type. I can create a separate question for this on SO.
@Tuzo - Also, i guess I can add multiple rulesets to properties by doing something like this? [VerifyValidState(Ruleset="State")] [VerifyValidState()] [VerifyValidState(Ruleset="SomeOtherRuleset")] public string State { get; set; }
@user102533 - Yes, you can add multiple RuleSets to properties.
Tuzo
@user102533 - You can use rules specified by attributes alongside rules specified via configuration for the same RuleSet. EL will run all rules for the RuleSet.
Tuzo