You have already learned how to implement validation in the MVC tutorials section. Here, we will enable client-side validation.
ASP.NET MVC supports client-side validation using jQyery. First, you need to take a reference of two javascript files from the Scripts folder, jquery.validate.unobtrusive.js (jquery.validate.min.js and jquery.validate.unobtrusive.min.js are minified files) in your layout file as shown below.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
@Html.Partial("_HeaderNavBar");
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
Now, add the following two settings in the <appSettings>
section of web.config, if they are not there.
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
That's it. You will get validation error messages onblur event of particular textfield on which you have applied the data annotations validation attribute.
Enabling client-side validation for a specific view
You can enable client-side validation for a specific view only by adding Html.EnableClientValidation(true) at the top on the view page.
@{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
Html.EnableClientValidation(true);
}
- Difference between Html.Partial() and Html.RenderPartial() in ASP.NET MVC
- Difference between Html.RenderBody() and Html.RenderSection() in ASP.NET MVC
- How to pre-compile razor view in ASP.NET MVC?
- How to enable bundling and minification in ASP.NET MVC?
- How to display an error message using ValidationSummary in ASP.NET MVC?
- How to bind a model to a partial view in ASP.NET MVC?
- View in ASP.NET MVC