如果有多个复选框,则Kendo验证程序始终返回false

时间:2019-04-08 20:26:18

标签: asp.net-mvc kendo-ui kendo-asp.net-mvc kendo-validator

在ASP.NET中,我具有以下内容

public class TestController : Controller
{
    public IActionResult Index()
    {
        return View(new MyModel()
        {
            Activities = new Activity[]
            {
                new Activity(){ },
                new Activity(){ }
            }
        });
    }
}

public class MyModel
{     
    public IList<Activity> Activities { get; set; }
}

public class Activity
{
    public bool IsActive { get; set; }
}

cshtml

@model Metatasker.Integration.UI.Controllers.MyModel

<form id="myform">
    @for (int i = 0; i < Model.Activities.Count; i++)
    {
        @Html.CheckBoxFor(x => x.Activities[i].IsActive)
    }
</form>
<button id="btn">Click Me</button>

<script type="text/javascript">
    $(function () {
        function validate() {
            var kendoValidator = $('#myform').kendoValidator().data("kendoValidator");
            return kendoValidator.validate();
        }

        $("#btn").click(function () {
            alert(validate());
        })
    })
</script>

我正在使用Kendo的Validate方法来验证表单。在上面的代码中,当我有多个CheckBox时,validate()方法始终返回false。如果我有一个复选框,那么它可以工作。

我有jsfiddle演示。 jsfiddle中的html是渲染的Razor视图。

DEMO

1 个答案:

答案 0 :(得分:0)

尝试以下代码段。

 <form id="form1">
      <!-- Kendo UI Checkbox -->
      <input type="checkbox" id="checkboxMale" name="Gender" required />
      <label for="checkbox">Male</label>
      <span class="k-invalid-msg" data-for="Gender"></span>
      <input type="checkbox" id="checkboxFemale" name="Gender" required />
      <label for="checkbox">Female</label>
      <span class="k-invalid-msg" data-for="Gender"></span>
     <button>Validate</button>
    </form>

    <script>
      $(document).ready(function() {
        var validator = $("#form1").kendoValidator().data("kendoValidator");
      });
    </script>

您会注意到,验证器仅将真实值作为已填充的输入,否则它将提供所需的验证消息。每个复选框都经过单独验证。

所以,我建议使用custom rule

<form id="myform">
    <ul validationMessage="You must enter a gender">
      <li>
        <input id="activity1" name="activity" type="checkbox" value="activity1" />
        <label  for="activity1">Activity1</label>
      </li>
      <li>
        <input id="activity2" name="activity"  type="checkbox" value="activity2" />
        <label for="activity2">Activity2</label>
      </li>
    </ul>
    <button>Validate</button>
</form>

<script>
    $("#myform").kendoValidator({
      rules: {
        customRule1: function(input) {          
          if (input.is("[name=activity]")) {
            return $("[name='activity']:checked").length > 0;
          }
        }
      },
      messages: {
        customRule1: "Atleast one activity should be selected."
      }
    });
</script>

还有一个demo which uses radio buttons,您可以参考。