Saturday, October 26, 2013

Enable /Disable Validation in WPF

Some time it is business requirement to temporarily suspend validation, recently I come across this situation so as all developer do I took the lazy way and try to find solution in web but I didn't find any suitable solution so I have decided to write my own. You can download the complete source code form hear.     




using System;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Windows.Controls;

namespace EnableDisableValidation.ValidationRules
{
    public class ValidateContactNumber : ValidationRule
    {

        public ValidateContactNumber()
        {
            this.IsValidate = true;
        }

        /// <summary>
        /// Get or Set the is validate.
        /// </summary>
        public Boolean IsValidate { get; set; }

        /// <summary>
        /// Implementation of phone number validation.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="cultureInfo"></param>
        /// <returns></returns>
        /// <Developer>Kaushik Kumar Mistry</Developer>
        /// <DateCreated>25 May 2013</DateCreated>
        /// <ModifiedBy>...</ModifiedBy>
        /// <ModifiedDate>...</ModifiedDate>
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            ValidationResult result = new ValidationResult(true, null);

            if (this.IsValidate)
            {
                String strContactNumber = value as String;

                if (String.IsNullOrEmpty(strContactNumber))
                    result = new ValidationResult(true, null);

                else if (Regex.IsMatch(strContactNumber, @"^\d{3}-?\d{3}-?\d{4}$") == false)
                    result = new ValidationResult(false, "Invalid Phone number.");

            }
            return result;
        }
    }
}


As you can see if the rule is active then it will simply return a ValidationResult so everything will be as though as you didn’t have validation rules in xaml.