maandag 9 mei 2011

How to perform Cross Field validation in silverlight

When validating properties in Silverlight in some rare occasions we want to only validate properties referential to other properties in our viewmodel / entity.  If you do not know how to implement validation using data annotations in Silverlight then please take a look at this article .  It provides a good lead on how to do this.

So imagine we have some kind of parking application that allows a user to park using a beneficial rate when he has a child younger than 5 years old.  So if we would have a simple viewmodel that would accommodate this it would look something like this:

    public class ParkingViewModel : VMBase
    {
        private string _kidsSsn;
        private bool _parkWithBenificialRate;

        [RequiredWhenParkingWithBenificialRate()]
        public string KidsSsn
        {
            get { return _kidsSsn; }
            set
            {
                _kidsSsn = value;
                RaisePropertyChanged(() => KidsSsn);
            }
        }

        public bool ParkWithBenificialRate
        {
            get { return _parkWithBenificialRate; }
            set
            {
                _parkWithBenificialRate = value;
                RaisePropertyChanged(() => ParkWithBenificialRate);
                RaisePropertyChanged(() => KidsSsn);
            }
        }

        public bool ChildIsUnderFiveYearsOld(string ssn)
        {
            // Retrieve some value from a service
            return ssn.Equals("1234567");
        }

        public RelayCommand Pay
        {
            get
            {
                return new RelayCommand(() =>
                                            {
                                                // Empty his bank account
                                            });
            }
        }
    }

We would then need to have a validation attribute that can do 2 things:
  • Check if the user is trying to park with a beneficial rate
  • Check if the social security number is of a child younger than 5 years old

    public class RequiredWhenParkingWithBenificialRateAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            // Get the parent type
            var vm = validationContext.ObjectInstance as ParkingViewModel;
           
            if(vm != null && vm.ParkWithBenificialRate)
            {
                if(!vm.ChildIsUnderFiveYearsOld(value.ToString()))
                {
                    return new ValidationResult("Child must be under five years old!!!",
                                                new [] {validationContext.MemberName});
                }
            }

            return ValidationResult.Success;
        }
    }
 
That’s it!

Geen opmerkingen:

Een reactie posten