an ASP.NET, C# technical blog, by Gianni Tropiano

The power of CustomValidator - Validate selected checkboxes

by CodeGolem 4. April 2009 12:48

** You can read also this newer post about Writing a reusable CheckBoxValidator. **

Here we go again with the CustomValidator.

This time we will try to validate a maximum number of checkboxes selected in the page.

Let's start with a CheckBoxList and a submit button on our page.


<asp:CheckBoxList runat="server" ID="ChexkBoxList" />
<asp:CustomValidator
    runat="server"
    ID="MyCustomValidator"
    OnServerValidate="MyCustomValidator_ServerValidate"
    ErrorMessage="Select max 2"
    />
<asp:Button runat="server" Text="Submit" />
 

We will populate the CheckBoxList on page load with a simple string array.


protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string[] values = new string[] { "CheckBox 1", "CheckBox 2", "CheckBox 3" };
        ChexkBoxList.DataSource = values;
        ChexkBoxList.DataBind();
    }
}
 

Now we are going to add our server-side custm validation (a must!).


protected void MyCustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
    int count = 0;
    foreach (ListItem item in ChexkBoxList.Items)
        if (item.Selected)
            count++;

    args.IsValid = count <= 2;
}

 

This will loop through the items of the CheckBoxList and count the selected ones.
The validation is successful if the selected items count is not greater than the desired value.
Our server-side validation is complete.

Let's add a client-side validation logic (nice-to-have).

We need a javascript function that will keep count of the selected checkboxes on the client, and will store that value in a HiddenField:


<asp:HiddenField runat="server" ID="SelectedCheckBoxesCount" Value="0" />


<script type="text/javascript">
    function onCheckBoxCheck(item) {
        var selectedCheckBoxesCount = document.getElementById('<%= SelectedCheckBoxesCount.ClientID %>');
        var count = Number(selectedCheckBoxesCount.value);
        if (item.checked)
            count += 1;
        else
            count -= 1;

        selectedCheckBoxesCount.value = count;
    }
</script>

This function needs to be called on each checkbox click, so we need to add the handler to each item in the CheckBoxList.
This must be done after binding the datasource to the list.
Here is the new page load event handler.


protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string[] values = new string[] { "CheckBox 1", "CheckBox 2", "CheckBox 3" };
        ChexkBoxList.DataSource = values;
        ChexkBoxList.DataBind();

        foreach (ListItem item in ChexkBoxList.Items)
            item.Attributes["onclick"] = "onCheckBoxCheck(this)";

    }
}

One more step, create the client-side validation function and bind it to the custom validator.
It will verify the hiddenfield's value and validate it if it is less or equal to the desired value.


<script type="text/javascript">
    function checkBoxListValidation(sender, args) {
        var selectedCheckBoxesCount = document.getElementById('<%= SelectedCheckBoxesCount.ClientID %>');
        var count = Number(selectedCheckBoxesCount.value);

        args.IsValid = count <= 2;
    }
</script>


<asp:CustomValidator
    runat="server"
    ID="MyCustomValidator"
    OnServerValidate="MyCustomValidator_ServerValidate"
    ErrorMessage="Select max 2"
    ClientValidationFunction="checkBoxListValidation"
    />

Good, we are done!

Obviously we can use this mechanism to validate for any number of selected checkboxes, for a minimum amount, or even for a range (select at least two, but maximum 4).

Tags: ,

ASP.NET

Comments


Republic of the Philippines nunny 
July 9. 2009 14:29
pure code bro


Denmark Acai Berry 
July 22. 2009 11:21
Good post, I will mention it on my blog.. Cheers


United States devix 
July 28. 2009 16:53
Thanks for sharing this code


United States Rick 
October 9. 2009 18:41
Question, why do we need server side validation if the client side validation will prevent posting?


Italy codegolem 
October 9. 2009 19:25
Hi Rick!

The answer is simple: we can not rely only on client-side validation.
The client browser could have javascript support disabled, or it could even not support it at all. Or maybe the POST is coming from a different source, not from a browser...

This note comes from an MSDN article about client and server validation:

Modern browsers that support scripting can be used to enhance the user experience by validating input before it is even submitted to the server. Validation on the client provides a convenient way for the user to correct input mistakes and prevents unnecessary round trips to the server.

However, validation on the client cannot be trusted as a security measure, because it is trivial for malicious users to send an HTTP query that bypasses the validation code contained in script, so server-side validation is still essential.


Hope this answers your question! Bye!


United States เล่นเกมส์ฟรี 
June 5. 2010 23:27
good work, will back soon, great site congratulation!!

Add comment



  Country flag

biuquote
  • Comment
  • Preview
Loading



Recent Posts

Sponsored By

iziCommerce

e-commerce has

never been so izi!

Try our online store!