Validate a Telerik RadTreeView

Created: December 23, 2014 Tagged As: ASP.net, Telerik, Web Forms Share:

The Telerik RadTreeView control offers a convenient way to present tree-based information. With the CheckBoxes property set to true, the user can select one or more nodes in the tree. This is really nice when choosing options that are in a hierarchical form. But how can we make sure that a user selects at least one node? The CustomValidator control and some JavaScript.

The Control Definitions:

<telerik:RadTreeView runat="server" ID="Tree" ViewStateMode="Disabled" CheckBoxes="true" CheckChildNodes="true" /> 
<asp:CustomValidator runat="server" EnableClientScript="true" ErrorMessage="Please select one or more nodes"  
      ClientValidationFunction="validateTree" ViewStateMode="Disabled" Display="Dynamic" />

The JavaScript:

<script type="text/javascript">
function validateTree(source, args)
{
   var tree = $find('<%=Tree.ClientID%>');
   if (tree.get_checkedNodes().length == 0)
      args.IsValid = false;
   else
      args.IsValid = true;
}
</script>

Notes:

  1. The ControlToValidate property is left blank on the CustomValidator intentionally. If it is filled in then the validation function does not fire since there is a pre-test that determines if the control is blank or not. In this case, that test will obviously fail. By leaving ControlToValidate blank that test is bypassed and validateTree is always called.
  2. If you make to make sure that a certain number of nodes are checked, change the length test from length == 0 to some other condition.