Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate checkbox with jquery.validate.unobtrusive

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()
like image 466
hmahdavi Avatar asked Jul 19 '17 11:07

hmahdavi


People also ask

What does JQuery validate Unobtrusive do?

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.”

What is validator unobtrusive parse?

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.

How do I make at least one checkbox required in JQuery?

JQuery Codeready(function(){ $("form"). submit(function(){ if ($('input:checkbox'). filter(':checked'). length < 1){ alert("Please Check at least one Check Box"); return false; } }); });

What is Unobtrusive JavaScript in MVC?

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.


1 Answers

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>
like image 188
Rory McCrossan Avatar answered Sep 18 '22 02:09

Rory McCrossan