How to Enable and Disable Client-Side Validation in MVC

Tuesday 12 May 2015
MVC3 & MVC4 supports unobtrusive client-side validation. In which validation rules are defined using attributes added to the generated HTML elements. These rules are interpreted by the included JavaScript library and uses the attribute values to configure the jQuery Validation library which does the actual validation work. In this article, I would like to demonstrate various ways for enabling or disabling the client side validation.

Enable Client-Side Validation in MVC

For enabling client side validation, we required to include the jQuery min, validate & unobtrusive scripts in our view or layout page in the following order.
  1. <script src="@Url.Content("~/Scripts/jquery-1.6.1.min.js")" type="text/javascript"></script>
  2. <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
  3. <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
The order of included files as shown above, is fixed since below javascript library depends on top javascript library.

Enabling and Disabling Client-Side Validation at Application Level

We can enable and disable the client-side validation by setting the values of ClientValidationEnabled & UnobtrusiveJavaScriptEnabled keys true or false. This setting will be applied to application level.
  1. <appSettings>
  2. <add key="ClientValidationEnabled" value="true"/>
  3. <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  4. </appSettings>
For client-side validation, the values of above both the keys must be true. When we create new project using Visual Studio in MVC3 or MVC4, by default the values of both the keys are set to true.
We can also enable the client-side validation programmatically. For this we need to do code with in the Application_Start() event of the Global.asax, as shown below.
  1. protected void Application_Start()
  2. {
  3. //Enable or Disable Client Side Validation at Application Level
  4. HtmlHelper.ClientValidationEnabled = true;
  5. HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
  6. }

Enabling and Disabling Client-Side Validation for Specific View

We can also enable or disable client-side validation for a specific view. For this we required to enable or disable client side validation inside a Razor code block as shown below. This option will overrides the application level settings for that specific view.
  1. @model MvcApp.Models.Appointment
  2. @{
  3. ViewBag.Title = "Make A Booking";
  4. HtmlHelper.ClientValidationEnabled = false;
  5. }
  6. ...

No comments:

Post a Comment

Sharing

Get widget