How to Add an Error Message to a ValidationSummary Progrommatically

For a while now I had been annoyed at the fact that there is no easy way to add an error message to a ValidationSummary control... Or at least I didn't think that there was, but it turns out that it's quite simple:

            RequiredFieldValidator Validator = new RequiredFieldValidator();
            Validator.ErrorMessage = "This is your error message";
            Validator.ValidationGroup = "Group1";
            Validator.IsValid = false;
            Validator.Visible = false;
            Page.Form.Controls.Add(Validator);

The error message and the validation group needs to be changed but basically this just creates a required field validator. It then says that the validator isn't valid and makes it invisible. However since we have a ValidationSummary object, it will show up there (assuming we set up the validation group properly). That's all there is to it. Anyway, I hope this helps out someone so you're not banging your head against a wall like I was. 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/21/2009 at 10:15 AM
Tags: , , ,
Categories: ASP.Net
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

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

Server side validation in ASP.Net

One of the items I was extremely happy to have before me when I switched to ASP.Net was the various validators. The fact that I didn't have to write my own code, nor use a third party library to accomplish validation of user entered information was fantastic. The main issue though is the fact that they're all client side. This means that while you can make sure the data is in the correct format, you can't check to see if the information already exists, if it points to a valid location (fake email/urls), etc. without a post back.

The post back gets rather annoying though for the end user, but thankfully there's AJAX. Thanks to AJAX, we have a couple of options: using UpdatePanels, AJAX calls, or building an extender. And since I'm lazy and like to reuse everything (not to mention I wanted the item to run with decent speed), I created a very basic extender.

ServerSideValidatorExtender.zip (2.14 kb)

The version here is extremely basic and can definitely be improved upon. However it takes in a control and when it is changed, it does a call back to a function specified with the value within the item. The function returns a boolean value (true if the value is OK, false otherwise) and displays an error message as needed. Once again, it's extremely basic and could use some extra features (such as displaying something during the call, maybe an option for success text, etc.). Anyway, download it, 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: 8/13/2008 at 2:38 PM
Tags: , ,
Categories: AJAX | ASP.Net | Web Design
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed