Using Conditions

Rules can be applied depending on conditions. Conditions are defined using 'If', 'Else' and 'EndIf' constructs.
This sample shows how a PhoneNumber Class can have different rules applied based on it's CountryCode.

    class Program
    {
        public class PhoneNumber
        {
            public int CountryCode { get; set; }
            public int AreaCode { get; set; }
            public int Number { get; set; }
        }

        static void Main(string[] args)
        {
            Engine engine = new Engine();
            engine.For<PhoneNumber>()
                .Setup(ph => ph.Number)
                    .MustBeGreaterThan(0)
                .If(ph => ph.CountryCode == 61)
                    .Setup(ph => ph.AreaCode)
                        .MustBeOneOf(2, 3, 4, 7, 8)
                .EndIf()
                .If(ph => ph.CountryCode == 33)
                    .Setup(ph => ph.AreaCode)
                        .MustBeBetween(1, 9)
                .Else()
                    .Setup(ph => ph.AreaCode)
                        .MustEqual(0)
                .EndIf();

            var phFrance = new PhoneNumber { CountryCode = 33, AreaCode = 2, Number = 1234 };
            var phAustralia = new PhoneNumber { CountryCode = 61, AreaCode = 5, Number = 1234 };
            var phVanuatu = new PhoneNumber { CountryCode = 678, AreaCode = 9, Number = 1234 };

            //France is valid...
            bool isValidFrance = engine.Validate(phFrance);

            //Australia is invalid (wrong area code)...
            bool isValidAustralia = engine.Validate(phAustralia);

            //Vanuatu is invalid (must be 0 for AreaCode)
            bool isValidVanuatu = engine.Validate(phVanuatu);
        }
    }

Last edited Sep 5, 2011 at 12:48 PM by athoma13, version 1

Comments

No comments yet.