Unplanned
Last Updated: 04 Feb 2021 00:42 by Hugo Augusto
Rob
Created on: 25 May 2020 11:24
Category: MultiSelect
Type: Feature Request
3
RadMultiSelect integration with RequiredFieldValidator and ControlToValidate property

A "Control 'RadMultiSelect1' referenced by the ControlToValidate property of 'MultiSelectValidator1' cannot be validated" error is thrown when the RadMultiSelect id is passed to the ControlToValidate property of the RequiredFieldValidator or CustomValidator.

Workaround: Using a CustomValidator with no ControlToValidate

<telerik:RadMultiSelect ID="RadMultiSelect1" runat="server" DataTextField="text" DataValueField="value">
    <Items>
        <telerik:MultiSelectItem Text="Item 1" Value="1"></telerik:MultiSelectItem>
        <telerik:MultiSelectItem Text="Item 2" Value="2"></telerik:MultiSelectItem>
        <telerik:MultiSelectItem Text="Item 3" Value="3"></telerik:MultiSelectItem>
    </Items>
</telerik:RadMultiSelect>

<telerik:RadButton runat="server" ID="RadButton1" Text="Postback" AutoPostBack="true" />

<asp:CustomValidator ErrorMessage="Please select an item" ClientValidationFunction="ClientValidationFunction" runat="server" />
<script>
    function ClientValidationFunction(sender, args) {
        var multiselect = $find("<%= RadMultiSelect1.ClientID %>");

        if (multiselect.get_value().length == 0) {
            args.IsValid = false;
        }
    }
</script>

1 comment
Hugo Augusto
Posted on: 04 Feb 2021 00:42

This solution is fine for just one control, but if you have multiple RadMultiSelect controls, you will need a more generic approach:

 

Here's my easy solution to be able to access the control to validate on client side.
Add the regular Custom Validator control with the options you might need.

    <asp:CustomValidator ID="cvalShippingRegionCountries" ErrorMessage="Choose a country" ClientValidationFunction="ClientValMultiSelectCountries" runat="server" Display="Dynamic" SetFocusOnError="true" /> 

Then, in code behind, just add a custom attribute to store the clientID of the MultiSelect control to validate.

    cvalShippingRegionCountries.Attributes.Add("ControlToValidateClientID", multiselectShippingRegionCountries.ClientID);

Now, in the function that deals with the validation you can access the value like this:

   function ClientValMultiSelectCountries(sender, args) {

            var multiselect = $find(sender.attributes.controltovalidateclientid.nodeValue);

            if (multiselect.get_value().length == 0) {
                args.IsValid = false;
            }
        }

You will get the clientID inside your generic function ;)