I found a very interesting problem in ASP.NET Core. I am using my bool field for a checkbox. I want to force the user to check the checkbox for the form to be submitted.
This bool field in my Model class is:
[Range(typeof(bool), "true", "true", ErrorMessage = "You must accept the Terms")]
public bool TermsAccepted { get; set; }
Notice I have applied [Range] validation attribute. And it works perfectly for the Server side validation.
My action method code is fairly simple:
[HttpPost]
public IActionResult Index(JobApplication jobApplication)
{
if (ModelState.IsValid)
return View("Accepted", jobApplication);
else
return View();
}
But the problem is happening when I apply client side validation
On my view i apply the 3 scripts:
@section scripts {
<script src="/lib/jquery/dist/jquery.min.js"></script>
<script src="/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="/lib/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.min.js">
</script>
}
The client side validation works totally opposite, it is giving error message when I check the checkbox. Why it is happening opposite?
The HTML code produced by the checkbox is:
<input type="checkbox" class="input-validation-error" data-val="true" data-val-range="You must accept the Terms" data-val-range-max="True" data-val-range-min="True" data-val-required="The TermsAccepted field is required." id="TermsAccepted" name="TermsAccepted" value="true" aria-describedby="TermsAccepted-error">
Please help?