Validating Expressions

Rules for an object as a whole

Some situations require validation rules the or for the object as a whole, and not just a single property. SpecExpress treats properties as an expressions. So, you don't need to take a different approach.

public class CreditRequestSpecification: Validates<CreditRequest>
{
    public CreditRequestSpecification()
    {
        Check(c => c.FirstName).Required();
        Check(c => c.LastName).Required();
        Check(c => c.Address).Required().Specification<AddressSpecification>();

        //Check Credit Score - example of "propertyless rule"
        Check(c => c, "Credit Score").Required().Expect( (contact,c) => CreditService.GetCreditScore(c) > 650, "Credit Score too low");
    }
}

Collections

Another use for this may be rules for a collection as a whole, and not just the items in them.

public class  FamilySpecification: Validates<Family>
{
    public FamilySpecification()
    {        
        //If the Family is 'Big', then the number of Children must be greater then 5
        Check(c => c.FamilyMembers.Where( f => f.MemberType == "Child"), "Number of Children in Family
             .If( c.FamilyType == "Big").Required()
             .CountGreaterThan(5);
    }
}

Note: If you use an Expression instead of a Property to evaluate, you will need to supply a Property Name to use the error messages.

Last edited Mar 19, 2010 at 8:16 PM by TechnoAg, version 3

Comments

No comments yet.