I use .NET Framework 4.7 with ASP.NET MVC to generate Forms and for validating I have JQuery Validate, which works for classic input fields, but for @Html.CheckBoxFor it generated 2 inputs with the same name, the first is standard input, the second is hidden, it is default by .NET, but JQuery validate does not work with this.
Only what works for me is adding validation rule for a specific element, but this approach does not delegate message, only apply the CSS class style to add red background to invalid input
What works but is not ideal solution yet
$("input[name='Do[0].IsSelected']:not(:hidden)").rules("add", { required: true, messages: { required: 'field is required.' } });
What does not work for JQuery Validation:
C# code:
<div class="col-lg-7 do-checkbox">
@Html.CheckBoxFor(m => m.Do[i].IsSelected, isViewModeForCheckBox, new { id = "chb_do" + i, onchange = "RemoveUpload(" + i + ");", @class = "form-check-input" })
@Model.Do[i].Text
</div>
Which generates this HTML output:
<div class="col-lg-7 do-checkbox">
<input class="form-check-input" data-val="true" data-val-required="The IsSelected field is required." disabled="" id="chb_do0" name="Do[0].IsSelected" onchange="RemoveUpload(0);" readonly="" type="checkbox" value="true" aria-invalid="true">
<label id="Do[0].IsSelected-error" class="border-danger shadow-danger" for="Do[0].IsSelected" style="display: none;"></label>
<input name="Do[0].IsSelected" type="hidden" value="false" class="valid">
Info text
</div>
JQuery validate:
$("form[name='reg']").validate({
ignore: ":hidden",
errorClass: "border-danger shadow-danger",
errorPlacement: function () { },
rules: {
"Reg.Name" : "required",
"Do[0].IsSelected": {
required: true,
email: function (element) {
return $("input[name='Do[0].IsSelected']:not(:hidden)").is(":checked");
}
},
},
messages: {
"Reg.Name": "Info error message",
"Do[0].IsSelected": {
required: "Enter a username",
email: "Enter at least {0} characters",
},
},
invalidHandler: function (event, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'Info 1 field missing'
: 'Info ' + errors + ' fields missing';
if (validator.errorList.length > 0) {
for (x = 0; x < validator.errorList.length; x++) {
message += "</br>\n\u25CF " + validator.errorList[x].message;
}
}
$("div.error span").html(message);
$("div.error").show();
} else {
$("div.error").hide();
}
},
submitHandler: function () {
document.forms["reg"].submit();
}
});
Jquery validate add CSS class to second hidden input, and not show message I also use additionals.methods.js extension library, but without success
from JQuery Validate and C# ASP MVC problem with Html.CheckBoxFor
No comments:
Post a Comment