我一直在寻找一种在“Checkbox”表单输入类型上生成“必需”jQuery消息的方法。
所有其他都可以,标准的“文本”输入类型,“选择”输入类型,“单选按钮”输入类型。但我还没有“Checkbox”输入类型。
我在哪里放一个:data-val="true" data-val-required="Please check at least one"
在下面的区块?
或者可能首先有一些“准备”语法?
<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>
关键是只有在您确认选中了复选框后才能通过代码提交表单。它会显示一条消息,如果未选中该复选框,则不会提交表单。
<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>
}