Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Treeview validation

The treeview has leaf node checkboxes.I need to validate the treeview if atleast one of the node is checked and not more than a specfic(say 3 nodes) number of nodes a user can select. Note:The Treeview is a asp.net treeview(not an ajax treeview)


1 Answers

Alright, since you didn't mentioned what type of validation you want, I'll do both client side and server side. My TreeView is named tvTest
First, add a CustomValidator to you Asp.Net page:

<asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="ClientValidate"
  ErrorMessage="CustomValidator" Display="Dynamic" OnServerValidate="CustomValidator1_ServerValidate">*</asp:CustomValidator>

Note: don't set the ControlToValidate property.
Next, add this script (also to your Asp.Net page) for client side validation:

<script type="text/javascript">

  function ClientValidate(source, arguments) {
    var treeView = document.getElementById("<%= tvTest.ClientID %>");
    var checkBoxes = treeView.getElementsByTagName("input");
    var checkedCount = 0;
    for (var i = 0; i < checkBoxes.length; i++) {
      if (checkBoxes[i].checked) {
        checkedCount++;
      }
    }
    if (checkedCount > 0 && checkedCount < 4) {
      arguments.IsValid = true;
    } else {
      arguments.IsValid = false;
    }
  }        

</script>

And last, add this to your code-behind for server side validation:

protected void CustomValidator1_ServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs args) {
  if (tvTest.CheckedNodes.Count > 0 && tvTest.CheckedNodes.Count < 4) {
    args.IsValid = true;
  } else {
    args.IsValid = false;
  }
}

Of course, you'll want to change the limits for the minimum and maximum number of nodes the user can check.

like image 107
Julien Poulin Avatar answered Aug 10 '26 14:08

Julien Poulin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!