Saturday, 22 December 2018

How to enable client side validation in asp.net MVC

To enable client side validation in MVC we need to enable ClientValidation and UnobtrusiveJavaScript in the web.config file as below.

<appSettings>
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

Once enabled in web.config we need to refer a set of.JS file in a proper sequence as they are interdependent. 

<script src="~/Scripts/jquery-3.0.0.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>

Else you can add these files in BundleConfig.cs file to avoid the repetition in each view where you want to enable client-side validation as below. With these changes, client-side validation will work. But if Javascript was disabled in your browser it will not work. So it is always suggested to check the browser if Javascript is enabled or not before loading the initial page or we can also apply both client-side validation and serverside validation in your application code.


        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));
 
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery.validate.min.js"));
 
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery.validate.unobtrusive.min.js"));
 
            bundles.Add(new ScriptBundle("~/bundles/jqueryui")
                        .Include("~/Scripts/jquery-ui-{version}.js"));
 
            bundles.Add(new StyleBundle("~/Content/jqueryui")
                            .Include("~/Content/themes/base/all.css"));
 
            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));
 
            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));
 
            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js"));
 
            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));
        }



No comments:

Post a Comment