Back To FAQ

Enable client side validation in MVC

You have already learned how to implement validation in MVC tutorials section. Here, we will enable client side validation.

ASP.NET MVC supports client side validation using jqyery. First of all you need to take a reference of two javascript files from Scripts folder, jquery.validate.unobtrusive.js (jquery.validate.min.js and jquery.validate.unobtrusive.min.js is minified files) in your layout file as shown below.

Example: Add jQuery Validation Script Files
<!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>&copy; @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 following two settings in <appSettings> section of web.config, if it is not there.

App Settings in web.config
<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 DataAnnotations validation attribute.

Enabling client side validation for a specific view

You can enable client side validation for specific view only by adding Html.EnableClientValidation(true) at the top in view page.

Razor Syntax:
@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
    Html.EnableClientValidation(true);
}