The layout file (_Layout.cshtml) defines the layout structure of your web application. As JavaScript libraries are going to be used in all the pages, this is the right place to add common functionalities such as unobtrusive validation.
Just add the JavaScript libraries (highlighted in bold in the following code snippet) to the layout file (_Layout.cshtml) so that they will be available for all the View files:
Go to https://goo.gl/MKJ39B to access the code.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
</head>
<body>
<div>
@RenderBody()
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.3.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/ 1.14.0/jquery.validate.min.js"> </script>
<script src="https://ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.min.js"></script>
</body>
</html>
There is no change to ViewModel except for the removal of the JavaScript function we wrote earlier for validating the fields. The complete code for the view is as follows:
Go to https://goo.gl/pxazJH to access the code.
@model MVCEF.ViewModels.EmployeeAddViewModel
@*
//For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}
...
...
</table>
</div>
The preceding diagram depicts the unobtrusive client validation process:
- Data Annotations are added to Model/ViewModels.
- The view takes Model/ViewModels and generates the HTML.
- The generated HTML from the ViewModel contains data-* attributes:
- For the fields for which the Required attribute is set, the data-val-required attribute is created with the error message as its value.
- For the fields with the MinLength Data Annotation attribute, the data-val-minlength attribute is set with the error message as its value.
- For the range, Data Annotation, the data-val-range attribute is set with the error message as its value. The data-val-range-max represents the maximum value in the range and the data-val-range-min attribute represents the minimum value in the range.
- The jQuery unobtrusive validation library reads these elements with data-* attributes and does the client-side validation. This means the developer does not have to write the separation validation code using JavaScript as everything is resolved by the configuration itself.
The data-val attributes are only generated from our pre-defined data attributes. If we had a complex custom logic and if we need
them to validate from the client side, then we need to go back to write JavaScript.
them to validate from the client side, then we need to go back to write JavaScript.