Combining Rules and Boolean Logic

Some properties require multiple rules be applied. SpecExpress rule expressions support And, Or and Not operations with operator precidence and even allows grouping of rules to control precidence.

And Operator

// RandomNumber must be between 5 and 10
Check(o => o.RandomInt).Required.GreaterThan(5).And.LessThan(10);

// An item's SerialNumber Length must be greater than or equal to 5 chars and less than or equal to 10 chars
Check(i => i.SerialNumber.Length(), "SerialNumber").Required.GreaterThanEqualTo(5).And.LessThanEqualTo(10);

Or Operator

// RandomNumber must be less than 5 or greater than 10
Check(o => o.RandomInt).Required.LessThanThan(5).Or.GreaterThan(10);

// An item's SerialNumber Length must be less than or equal to 5 chars or greater than or equal to 10 chars
Check(i => i.SerialNumber.Length(), "SerialNumber").Required.LessThanEqualTo(5).Or.GreaterThanEqualTo(10);

Not Operator

// RandomNumber must not be unlucky
Check(o => o.RandomInt).Required.Not.EqualTo(13);

Operator Precidence

Just like boolean logic in a C# expression, an And operator has precidence over an Or operator regardless of its position in the expression. The two rules below evalate the same way.

// RandomInt must be either less than 5 or between 10 and 100.
Check(o => o.RandomInt).Required.LessThan(5).Or.GreaterThan(10).And.LessThan(100);

// RandomInt must be between 10 and 100 or less than 5.
Check(o => o.RandomInt).Required.GreaterThan(10).And.LessThan(100).Or.LessThan(5);

Grouping

Sometimes one needs to control the precidence with groups.

// Serial numbers start with "x" or "y" and have a length of 10 chars
Check(i => i.SerialNumber).Required.Group(s => s.Matches("^x.*$").Or.Matches("^y.*$")).And.LengthEqualTo(10));

Last edited May 13, 2011 at 12:29 AM by rbell80134, version 3

Comments

No comments yet.