views:

24

answers:

0

I was playing with asp.net mvc 2's DataAnnotation validation. It hookup to the client side validation very nicely. I really like that I can just define one sets of rules and be able to user it at both client and server side.

I am wondering if it is possible to do it with asp.net form. The following code snippet shows how it is done, and it works fine for simple data validation on server side once the object is created.

However, I would like to reuse the validation checks on the client side (jQuery or asp.net's javascript library) so I don't have to define 2 sets of validation definition on sever/client.

[DataMember, DisplayName("Prop A Description")]
[Required(ErrorMessage = "PropertyA is required.")]
[RegularExpression(@"^[0-9]*(\.)?[0-9]+$", ErrorMessage = "PropertyA format invalid")]
public string Property { get; set; }

and I created the following method on the base class to do the validation

    public bool IsValid()
    {
        bool result = true;

        PropertyInfo[] properties = this.GetType().GetProperties();

        foreach (PropertyInfo property in properties)
        {

            //Get all the custom validation attributes
            var cusAttributes = property.GetCustomAttributes(typeof(ValidationAttribute), true).OfType<ValidationAttribute>();

            foreach (var attribute in cusAttributes)
            {
                //validate individual attribute base on it's custom attribute.
                Boolean isValid = attribute.IsValid(property.GetValue(this, null));

                //if attribute is not valid, log it to the ErrorMessage Collection
                if (!isValid)
                {
                    this.ErrorMessages.Add(new ErrorSummary() { ErrorMessage = attribute.ErrorMessage });
                    result = false;
                }
            }

        }
        return result;
    }