企业库验证块和规则集

时间:2010-04-05 14:56:49

标签: c# .net validation enterprise-library

我在类似的类型上使用Rulesets:

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; }
}

由于业务需求,我需要先验证规则集“State”,然后验证整个业务实体

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"

}

我如何完成我想要做的事情?

1 个答案:

答案 0 :(得分:3)

您需要将VerifyValidState添加到两个RuleSet:

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; }
}

然后你可以单独调用每个RuleSet(你已经在做了)。代码如下:

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)); 
    }    
}