Business Object Validation Using Attributes in C#

Ok, so there are about 9,000,000 different implementations out there when it comes to validating business objects. Although most of the ones that I see out there are simply tweeked versions of CSLA.Net. Personally I'm not a big fan of that approach. It works quite well but I just wanted to try something else, so instead I tried out the second most popular approach... Attributes. I know that usually I groan whenever I think about attributes but it actually works pretty well in this instance.

public class Test
{
    [Between(1,4,"This item needs to be between 1 and 4")]
    public int Value{get;set;}
}

That's not that bad. Even if I have ten properties, that isn't that bad. And implementing the attributes themselves is simple as well:

    [AttributeUsage(AttributeTargets.Property,AllowMultiple=false)]
    public class BaseAttribute:Attribute
    {
        public BaseAttribute(string ErrorMessage)
        {
            this.ErrorMessage = ErrorMessage;
        }

        public string ErrorMessage { get; set; }

        internal virtual string IsValid(PropertyInfo Property,object Object)
        {
            return ErrorMessage;
        }
    }

    public class Between : BaseAttribute
    {
        public Between(object MinValue,object MaxValue, string ErrorMessage)
            : base(ErrorMessage)
        {
            this.MinValue = MinValue;
            this.MaxValue = MaxValue;
        }

        public object MinValue { get; set; }
        public object MaxValue { get; set; }

        internal override string IsValid(PropertyInfo Property, object Object)
        {
            object Value = Property.GetValue(Object, null);
            if (Value is DateTime && (DateTime)Value <= DateTime.Parse(this.MaxValue.ToString()) && (DateTime)Value >= DateTime.Parse(this.MinValue.ToString()))
                return "";
            else if (Value is DateTime)
                return ErrorMessage;
            else if (double.Parse(Value.ToString()) <= double.Parse(this.MaxValue.ToString()) && double.Parse(Value.ToString()) >= double.Parse(this.MinValue.ToString()))
                return "";
            return ErrorMessage;
        }
    }

That's it, a constructor, some fields to hold our information, and one function. We do however have to find the attributes and call the function to even check the property, but with a bit of reflection that's pretty simple:

    public static class ValidationManager
    {
        public static bool Validate(object Object)
        {
            StringBuilder Builder = new StringBuilder();
            if (Object != null)
            {
                Type ObjectType = Object.GetType();
                PropertyInfo[] Properties = ObjectType.GetProperties();
                foreach (PropertyInfo Property in Properties)
                {
                    object[] Attributes = Property.GetCustomAttributes(typeof(BaseAttribute), true);
                    foreach (object Attribute in Attributes)
                    {
                        Builder.Append(((BaseAttribute)Attribute).IsValid(Property, Object));
                    }
                }
            }
            if(string.IsNullOrEmpty(Builder.ToString()))
                return true;
            throw new NotValid(Builder.ToString());
        }
    }

That's it really. We just call the Validate function, passing in our object, and in turn  the function gets all of the properties, finds the attributes, and calls the IsValid function appropriately. And because all of our attributes inherit from BaseAttribute, all we need to do is create a new one and the function will automatically pick it up. So if we want one based off of Regex for strings, not a problem:

    public class Regex:BaseAttribute
    {
        public Regex(string RegexString, string ErrorMessage)
            :base(ErrorMessage)
        {
            this.RegexString = RegexString;
        }

        public string RegexString { get; set; }

        internal override string IsValid(PropertyInfo Property, object Object)
        {
            object Value = Property.GetValue(Object, null);
            if (Value is String)
            {
                System.Text.RegularExpressions.Regex TempRegex = new System.Text.RegularExpressions.Regex(RegexString);
                if (TempRegex.IsMatch((string)Value))
                    return "";
            }
            return ErrorMessage;
        }
    }

Hell if we want to have the ability to cascade and check classes, we can:

    public class Cascade:BaseAttribute
    {
        public Cascade()
            : base("")
        {
        }

        internal override string IsValid(PropertyInfo Property, object Object)
        {
            object Value = Property.GetValue(Object, null);
            if (Property.PropertyType.FullName.StartsWith("System.Collections.Generic.List", StringComparison.CurrentCultureIgnoreCase))
            {
                Type ListType = Value.GetType();
                PropertyInfo IndexProperty = ListType.GetProperty("Item");
                PropertyInfo CountProperty = ListType.GetProperty("Count");
                int Count = (int)CountProperty.GetValue(Value, null);
                for (int x = 0; x < Count; ++x)
                {
                    object IndexedObject = IndexProperty.GetValue(Value, new object[] { x });
                    if (IndexedObject != null)
                    {
                        try
                        {
                            ValidationManager.Validate(IndexedObject);
                        }
                        catch (NotValid e) { return Property.Name + "(" + x + ") : " + e.Message; }
                    }
                }
            }
            else
            {
                if (Value != null)
                {
                    try
                    {
                        ValidationManager.Validate(Value);
                    }
                    catch (NotValid e) { return Property.Name + " : " + e.Message; }
                }
            }
            return "";
        }
    }

Heck in the one above, we can even check if this is a list and go through each item in the list... And when we're done creating the attribute, we just tack it on our properties and we're done. So try it out, leave feedback, and happy coding.

kick it on DotNetKicks.com   Shout it
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkListEmail

Posted by: James Craig
Posted on: 7/14/2009 at 8:02 AM
Tags: , , ,
Categories: C#
Post Information: Permalink | Comments (5) | Post RSSRSS comment feed

Comments

Stéphane Canada

Friday, January 15, 2010 11:19 AM

Stéphane

Good Job!

This is the most elegent way I found on the net to do this.
And you go further that the other examples.

Thanks!
Stéphane

James Craig United States

Friday, January 15, 2010 3:23 PM

James Craig

Thank you. I'm always a little surprised when my code helps someone out. If you want a more up to date version (or more examples), you can check the open source project that came out of this post: http://yabov.codeplex.com.

Mihai Romania

Thursday, July 01, 2010 1:46 AM

Mihai

Very helpful thx

Robert Macedonia (FYROM)

Friday, July 02, 2010 11:29 AM

Robert

very usefull thing...ok
you use named parametars...
I use all that validation in one class using  positional parameter...
point...less code...anyway great thing...bye

Qamar

Wednesday, July 07, 2010 7:55 AM

Qamar

I am going to fan of you. Your solution is generic and very help full. Thank you very much.

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading