Search code examples
asp.net-corerazorbootstrap-4jquery-validateunobtrusive-validation

ASP.Net Core Razor pages: how does <form class="needs-validation"> actually invoke client-side validation?


I'm working with a ASP.Net Core 3.1 web application.

If a Razor page has a form with class="needs-validation", then client-side validation is invoked for the fields in that form. Specifically, jquery-validation-unobtrusive gets called when the user clicks "Submit".

Q: How exactly does this occur? What "magic" links the HTML class "needs-validation" to the"validate()" Javascript code? Is there some CSS file somewhere that defines this linkage?

Q: Is "needs-validation" a Bootstrap class? Or is it standard HTML5/CSS3? Where/how is it defined?

These are some of the links I've found, but I still don't understand the linkage between class "needs-validation" invoking the validation code:


Solution

  • By default, asp.net core application use jQuery Unobtrusive Validation and https://jqueryvalidation.org/ plugin to achieve the client side validation. JQuery Unobtrusive Validation parses the data- attributes and passes the logic to jQuery Validation, effectively "copying" the server-side validation logic to the client. You can display validation errors on the client using tag helpers as shown here (without the class="needs-validation"):

        <form method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    
            <div class="form-group">
                <label asp-for="Movie.Title" class="control-label"></label>
                <input asp-for="Movie.Title" class="form-control" />
                <span asp-validation-for="Movie.Title" class="text-danger"></span>
            </div>
    
            <div class="form-group">
                <label asp-for="Movie.Description" class="control-label"></label>
                <input asp-for="Movie.Description" class="form-control" />
                <span asp-validation-for="Movie.Description" class="text-danger"></span>
            </div>
            ....
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    

    The class="needs-validation" is used for custom Bootstrap form validation messages (use HTML5 form validation), then, it will based on this class selector to find elements and validate the data. Check the Bootstrap Validation to learn how it works and how to use it.