How to enable client side validation in ASP.NET MVC?

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.

Example: Add jQuery Validation Script Files
<!DOCTYPE html>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    <div class="container body-content">
        <hr />
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
    @RenderSection("scripts", required: false)

Now, add the following two settings in the <appSettings> section of web.config, if they are not there.

App Settings in web.config
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>

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.

Razor Syntax:
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";