Client-side validation checks form values with JavaScript before sending them to the server. It gives users immediate feedback instead of making them wait for a request, server processing, and a response to discover a missing or invalid value. It complements server-side validation rather than replacing it. section 29.6 section 9.3.6
In ASP.NET Core, form tag helpers emit data-val* attributes describing field constraints. Microsoft's unobtrusive validation script reads those attributes and configures jQuery Validation, which performs the checks. The rules therefore appear in generated HTML rather than in a separate hand-written check for every input. section 29.6
To enable the supplied setup:
- Install jquery-validate and jquery-validation-unobtrusive with LibMan; install core jQuery too if it is not already present. section 29.6
- Load jQuery, jQuery Validation, and the unobtrusive script in that order. The shown _Validation.cshtml also adds Bootstrap’s is-invalid class to inputs already marked input-validation-error. section 29.6
Listing 29.24 Adding elements in the _Validation.cshtml file in the Views/Shared folder
<script type="text/javascript">
window.addEventListener("DOMContentLoaded", () => {
document.querySelectorAll("input.input-validation-error")
.forEach((elem) => { elem.classList.add("is-invalid"); }
);
});
</script>
<script src="/lib/jquery/jquery.min.js"></script>
<script src="/lib/jquery-validate/jquery.validate.min.js"></script>
<script src=
"/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js">
</script>
The shared _Validation.cshtml listing shows the script order and the small error-styling addition. section 29.6
A required field in the generated form
An input for Name can carry data-val="true" and data-val-required="Please enter a value". With the validation scripts loaded, those attributes provide the client-side rule. A checkout form submitted empty illustrates the slower server-side alternative: errors appear only after ASP.NET Core processes the submission. section 29.6 section 9.3.6
Keep authentication on the server. Checking credentials in the client would mean exposing valid credentials for comparison or trusting the client's claim that authentication succeeded. section 11.4







