What is Unobtrusive Validation in jQuery?
jQuery is a Javascript library. An unobtrusive validation in jQuery is a set of ASP.Net MVC HTML helper extensions.By using jQuery Validation data attributes along with HTML 5 data attributes, you can perform validation to the client-side.
Unobtrusive Validation means without writing a lot of validation code, you can perform simple client-side validation by adding the suitable attributes and including the suitable script files.
- jquery.validate.min.js
- jquery.validate.unobtrusive.js
These unobtrusive validation libraries need to be added:
Bower: bower install jquery-validation
NuGet: Install-Package jQuery.Validation
NPM : npm i jquery-validation
Installation via Package Managers:
- Required
- data-val-required=”This is required.”
- data-val=”true/false”
- EmailAddress
- data-val-email=”Error message”
MaxLength
- data-val-maxlength=”Error message”
- data-val-maxlength-max=”Maximum length (e.g. 5)”
- MinLength
- data-val-minlength=”Error message”
- data-val-minlength-min=”Minimum length (e.g. 2)”
List of some data validation attribute:
Method for unobtrusive validation:
Firstly, we need to add those libraries in the script of HTML files. These libraries provide a list of data attributes (data-val, data-val-required, and many more) for validation. Then the form should be built according to the requirements in which different types of data attributes can be used.
Example:
<!DOCTYPE html><html> <head> <!--These validation libraries need to be included for unobtrusive validation --> <script src= </script> <script src= </script> <script src= </script> </head> <body> <form id="myform"> <p> <label for="roll">Roll no.</label> <!-- data-val-required is used to specify the msg for each rule --> <!-- data-val is used to add rules to the input elements --> <input name="roll" type="number" data-val-required="Roll no. is required." data-val="true" style="margin-left: 15px;" /><br /> <span data-valmsg-for="roll" data-valmsg-replace="true" style="margin-left: 75px; color: red;" /> </p> <p> <label for="name">Name</label> <input name="name" type="text" data-val-required="Name is required." data-val="true" style="margin-left: 30px;" /><br /> <span data-valmsg-for="name" data-valmsg-replace="true" style="margin-left: 75px; color: red;" /> </p> <p> <label for="mobile">Mobile no.</label> <input name="mobile" type="number" data-val-required="Mobile no. is required." data-val="true" /><br /> <span data-valmsg-for="mobile" data-valmsg-replace="true" style="margin-left: 78px; color: red;" /> </p> <p> <label for="email">E-Mail </label> <input type="email" name="email" data-val-required="Email is required." data-val="true" style="margin-left: 30px;" /><br /> <span data-valmsg-for="email" data-valmsg-replace="true" style="margin-left: 80px; color: red;" /> </p> <p> <input class="submit" type="submit" value="Submit" /> </p> </form> </body></html> |
Output:
Before submit:

After submit:



