Monday, April 11, 2011

ASP.NET CheckboxList Validation with RequiredFieldValidator

In order to use a RequiredFieldValidator with a CheckBoxList, you need to define your own CheckBoxList class that inherits from CheckBoxList , but also implements a ValidationPropertyAttribute  method:


    [ValidationPropertyAttribute("ValidateableProperty")]
    public class ValidateableCheckBoxList : CheckBoxList
    {
 
        public string ValidateableProperty
        {
            get
            {
                string result = "";
                int count = 0;
                foreach (ListItem item in this.Items)
                {
                    if (item.Selected)
                    {
                        count++;
                    }
 
                }
                if (count > 0)
                {
                    result = count.ToString();
                }
                else
                {
                    result = "";
                }
                return result;
            }
        }
    }


You can then create a ValidateableCheckBoxList and point a required validator's controlToValidate attribute to it.

SOURCE:
http://pedroliska.wordpress.com/2009/08/13/getting-an-asp-net-checkboxlist-to-work-with-a-requiredfieldvalidator/

1 comment:

  1. Hi,

    This is very informative article. Thanks for sharing your knowledge. There are few links that also helpful for developers. This article have described to validate CheckBox, CheckBoxList, DropDownList, FileUpload, RadioButton, RadioButtonList, TextBox using jquery.

    http://mindstick.com/Articles/c3825daa-a449-467d-9513-34a8232d498a/?Validations%20on%20Asp%20Net%20Control
    http://www.aspdotnet-suresh.com/2012/09/jquery-validate-checkboxlist-in-aspnet.html

    ReplyDelete