This is a migrated thread and some comments may be shown as answers.

Validate no of selected items in MultiSelect-control

2 Answers 1900 Views
MultiSelect
This is a migrated thread and some comments may be shown as answers.
Johan
Top achievements
Rank 1
Johan asked on 17 May 2018, 06:44 AM

The MultiSelect-control is bound to a list of strings and it's required that the user select exactly four items.

How can I validate that with Kendo Validator or ASP.Net Validation?

I have also tried to use the Required annotation on the model property, but only that doesn't work.
Neither do the Range-keyword since it only works for numeric fields.

 

2 Answers, 1 is accepted

Sort by
1
Accepted
Ivan Danchev
Telerik team
answered on 18 May 2018, 02:22 PM
Hello Johan,

Here's an example showing how the Validator can be used in order to validate that 4 items are selected in the MultiSelect:
<div id="content">
    <button class="k-button">Validate</button>
     @(Html.Kendo().MultiSelect()
          .Name("people")
          .Placeholder("Select attendees...")
          .BindTo(new List<string>() {
              "Steven White",
              "Nancy King",
              "Anne King",
              "Nancy Davolio",
              "Robert Davolio",
              "Michael Leverling",
              "Andrew Callahan",
              "Michael Suyama",
              "Anne King",
              "Laura Peacock",
              "Robert Fuller",
              "Janet White",
              "Nancy Leverling",
              "Robert Buchanan",
              "Andrew Fuller",
              "Anne Davolio",
              "Andrew Suyama",
              "Nige Buchanan",
              "Laura Fuller"
          })
          .Value(new string[] { "Anne King", "Andrew Fuller" })
    )
    <span data-for="people" class="k-invalid-msg"></span>
</div>
<script>   
var validator = $("#content").kendoValidator({
  rules: {
    hasItems: function (input) {
      if(input.is("[name=people]")){
        var ms = input.data("kendoMultiSelect");
        if(ms.value().length != 4){
          return false;
        }
      }
      return true;
    }
  },
  messages: {
    hasItems: "Please select 4 people"
  }
}).data("kendoValidator");
 
$("button").click(function(){
  validator.validate();
});
</script>


Regards,
Ivan Danchev
Progress Telerik
Try our brand new, jQuery-free Angular components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
0
Johan
Top achievements
Rank 1
answered on 19 May 2018, 07:37 AM

Hi Ivan,

Aha, it is solved by creating a validation rule like that. 

I tried the code snippet and it works great =)

Thanks!

Tags
MultiSelect
Asked by
Johan
Top achievements
Rank 1
Answers by
Ivan Danchev
Telerik team
Johan
Top achievements
Rank 1
Share this question
or