jQuery validations =>复选框?

时间:2018-03-05 21:14:27

标签: jquery validation unobtrusive-validation

我一直在寻找一种在" Checkbox"上生成"必需",jQuery消息的方法。表格输入类型。

所有其他人都可以,标准"文字"输入类型,"选择"输入类型,"单选按钮"输入类型。但是,我还没有" Checkbox"输入类型。

我会在下一个区块放置一个:data-val="true" data-val-required="Please check at least one"

或者也许有一些" prep"语法第一?

  <script src="/forms/Scripts/jquery.validate.js"></script>
  <script src="/forms/Scripts/jquery.validate.unobtrusive.js"></script>

  <form>
  <...>
  <td valign="top">
    <input type="checkbox" name="audience" value="executives" >Executives <br />
    <input type="checkbox" name="audience" value="professionals">Professionals<br />
    <input type="checkbox" name="audience" value="practitioners">Practitioners

    <div class="col-sm-1 input">@Html.ValidationMessageFor(model => model.audience)</div>
</td>

1 个答案:

答案 0 :(得分:0)

关键是只有在您确认选中了复选框后才能通过代码提交表单。它会显示一条消息,如果未选中该复选框,则不会提交表单。

<form asp-action="Request">
    @*This is a work-around for a checkbox bug*@
    <style>
        .custom-control-label::before,
        .custom-control-label::after {
            top: .8rem;
            width: 1.25rem;
            height: 1.25rem;
        }
    </style>
    <div>
        <input asp-for="IAgree" type="checkbox" id="TermsCheck1" value="false" onclick="$('#Terms').hide();" />
        <input asp-for="IAgree" type="checkbox" id="TermsCheck2" value="false" onclick="$('#Terms').hide();" />

        <div id="Terms">Please confirm.</div>
    </div>
    <br />
    <div class="form-group">
        <button type="button" onclick="ValidateTerms()">
            Continue
        </button>
    </div>
</form>
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script>
        function ValidateTerms() {
            if ($('#TermsCheck1').prop('checked') || $('#TermsCheck2').prop('checked')) {
                $('form:first').submit();
            }
            else {
                $("#Terms").show();
            }
        }
    </script>
}