Treeview validation

荒凉一梦 提交于 2020-01-04 04:40:22

问题


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:


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.



来源:https://stackoverflow.com/questions/1048231/treeview-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!