Monday, April 18, 2011

c#: Custom Validation Example

Validation is a big thing for any application.  I am currently working on implementing validation in my WCF layer that doesn't rely on me checking each operation and then hardcoding validation logic into a gigantic class.  I really like the way WCF does model validation, so I decided to start trying to reproduce it to figure out how they did it.

It turns out that it is pretty simple as the following code suggests.  I created a base attribute called Validation Attribute.  I created a BaseModel that has a validate method on it.  That method does some simple reflection to get all the attributes for all the properties in the given class.  It just calls IsValid on those attributes to run the specified logic. 

Check it out.


    public class BaseModel
    {
        public bool Validate()
        {
            var result = true;

            foreach (var property in this.GetType().GetProperties())
            {
                foreach (var attribute in property.GetCustomAttributes(true))
                {
                    if (attribute is ValidationAttribute)
                    {
                        try
                        {
                            var attr = (ValidationAttribute)attribute;
                            result = result && attr.IsValid(property.GetValue(this, null));
                        }
                        catch (Exception)
                        {
                            result = false;
                        }
                    }
                }
            }

            return result;
        }
    }


    public class LoginModel : BaseModel
    {
        [UserNameValidation]
        public string UserName { get; set; }
    }

    [System.AttributeUsage(System.AttributeTargets.Property)]
    public class ValidationAttribute : Attribute
    {
        public virtual bool IsValid(object obj)
        {
            return false;
        }
    }

    public class UserNameValidationAttribute : ValidationAttribute
    {
        private const string USER_NAME_REGEX = @"^\w+$";

        public override bool IsValid(object obj)
        {
            if (obj == null)
            {
                return false;
            }

            var value = obj as string;
            
            if (Regex.IsMatch(value, USER_NAME_REGEX))
            {
                return true;
            }

            return false;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var loginModel = new LoginModel();
            loginModel.UserName = "UserName";
            Console.WriteLine(loginModel.Validate());
        }
    }