Validate no of selected items in MultiSelect-control

3 posts, 1 answers
  1. Johan
    Johan avatar
    6 posts
    Member since:
    Oct 2015

    Posted 17 May 2018 Link to this post

    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. Answer
    Ivan Danchev
    Admin
    Ivan Danchev avatar
    1749 posts

    Posted 18 May 2018 Link to this post

    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.
  3. Johan
    Johan avatar
    6 posts
    Member since:
    Oct 2015

    Posted 19 May 2018 in reply to Ivan Danchev Link to this post

    Hi Ivan,

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

    I tried the code snippet and it works great =)

    Thanks!

Back to Top