Samantha J T Star
Samantha J T Star

Reputation: 32818

Do I need to use three javascript libaries for validation with ASP.NET MVC4?

I would like to do validation of my form so I am looking at the ASP.NET MVC4 sample application.

Here I see it uses the following:

jquery.unobtrusive-ajax.js
jquery.validate.js
jquery.validate.unobtrusive.js

Can someone explain. Do I need all of these js libraries. I thought I read some place that one was now doing the job of the other but I see the sample still loads all three of them.

Upvotes: 0

Views: 221

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039110

Can someone explain. Do I need all of these js libraries.

No, absolutely not.

For jquery unobtrusive validation you need the following 3 scripts added in that particular order:

  1. jquery.js
  2. jquery.validate.js
  3. jquery.validate.unobtrusive.js

The jquery.unobtrusive-ajax.js script has absolutely nothing to do with validation. This is used by all the Ajax.* helpers (such as Ajax.BeginForm and Ajax.ActionLink).

Now, this being said, ASP.NET MVC 4 uses script bundles. For example when you create a new ASP.NET MVC 4 application using the Internet Template in Visual Studio it will create the ~/App_Start/BundleConfig.cs file for you containing the following registration:

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
            "~/Scripts/jquery.unobtrusive*",
            "~/Scripts/jquery.validate*"));

This means that out-of-the-box if inside your layout or view you call:

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")

you're gonna get in Debug mode:

<script src="/Scripts/jquery-1.7.1.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>

In Release mode (<compilation debug="false"> in your web.config) all those scripts will be minified, compressed and bundled into a single script served through a dynamic endpoint.

Upvotes: 4

Related Questions