How can enforce the required rule and if needed have an error display inside the SPAN tag?
Trying to add custom client side validation to a dotNET ASP MV* web page field Report.Name. For other reasons, I can’t add unobtrusive validation JQuery until a refactor is done. For now I’m trying to use JQuery validate. When I run a representation of the below code and submit with an empty field, I can get the fired events for showErrors and submitHandler. However, I’m not getting any invalid form errors. Methods this.valid() & this.numberOfInvalids() result in 0 as number of errors. The whole process just submits as if no errors exist.
Report.cshtml
<form method="post" id="formReport">
. . .
<div class="form-group">
<label asp-for="Report.Name" validation-for="Report.Name"></label>
<input type="text" class="form-control" data-val-required="The Report Name field is required." asp-for="Report.Name" />
<span asp-validation-for="Report.Name" class="text-danger"></span>
</div>
. . .
Rendered HTML:
<input type="text" class="form-control"
data-val-required="The Report Name field is required."
data-val="true"
data-val-maxlength="The field Report Name must be a string or array type with a maximum length of '35'."
data-val-maxlength-max="35"
id="Report_Name"
maxlength="35"
name="Report.Name" value="" />
JQuery:
$(document).ready(function () {
$("#formReport").validate({
submitHandler: function (form) {
this.valid();
var numOfErrors = this.numberOfInvalids();
alert("submitHandler: " + numOfErrors);
submitReport();
},
onsubmit: true,
rules: {
Report_Name: {
required: true
}
},
messages: {
Report_Name: {
required: "Testing: Report_Name required"
}
},
showErrors: function (errorMap, errorList) {
var numOfErrors = this.numberOfInvalids();
alert("showErrors: " + numOfErrors);
}
});
}
2
Answers
You must specify the exact name attribute of the
<input>
in the configuration."."
and"_"
are not interchangeable. Since you have a name that isn’t a valid identifier, you need to quote it.You can also consider using vanilla JavaScript. If the form should just submit to some URL you can leave out the last event listener (onsubmit).
The oninvalid event listener (second) depend on the attribute
required
on the input element. When this attribute is set the input will validate based on the maxlength attribute and will also assume that the value is not an empty string.