I need to validate lows checkbox with jquery.validate.unobtrusive
and I use this code but always checkbox is valid. How to solve this?
<input id="AcceptLaws" type="checkbox" name="AcceptLaws" data-val="true" data-val-required="Please accept with laws">
<span class="field-validation-valid" data-valmsg-for="AcceptLaws" data-valmsg-replace="true"></span>
$('#AcceptLaws').valid()
Unobtrusive Validation means without writing a lot of validation code, you can perform simple client-side validation by adding the suitable attributes and including the suitable script files. data-val-required=”This is required.”
validator. unobtrusive. parse(selector) method to force parsing. This method parses all the HTML elements in the specified selector and looks for input elements decorated with the [data-val=true] attribute value and enables validation according to the data-val-* attribute values.
JQuery Codeready(function(){ $("form"). submit(function(){ if ($('input:checkbox'). filter(':checked'). length < 1){ alert("Please Check at least one Check Box"); return false; } }); });
Unobtrusive Validation allows us to take the already-existing validation attributes and use them client-side to make our user experience that much nicer. The Unobtrusive script files are included automatically with new MVC projects in Visual Studio, but if you don't have them you can get them from NuGet.
The issue is because your data
attributes for the required rule are incorrect. You need to set data-rule-required="true"
, then put the error message in to data-msg-required
. Try this:
$('#AcceptLaws').valid()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<form>
<input id="AcceptLaws" type="checkbox" name="AcceptLaws" data-val="true" data-rule-required="true" data-msg-required="Please accept with laws" />
<span class="field-validation-valid" data-valmsg-for="AcceptLaws" data-valmsg-replace="true"></span>
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With