You are on page 1of 13

8/13/2017 ASP.

NET MVC 5 - JQuery Form Validator

ASP.NET MVC 5 - JQuery


Ask a QuestionForm Validator

Asma Khalid Mar 27 2017 Article

6 2 33.9k

JqueryFormValidator.zip
Download 100% FREE Spire O ce APIs

Form Component is an important portion on any website that requires data input from the end-user. It
could be an account creation form, feedback form, or any kind of information registration form etc. Since
the data required on forms is input by end-users, it is the responsibility of a web engineer to ensure the
kind of information the end-user is allowed to register. So, here comes Web Form Validation into play.

Web form validation is of two types i.e.

1. Client-side form validation


2. Server-side form validation

Client-Side Form Validation

This type of form validation is done at browser level, i.e., handling simple constraint validations; e.g. -
checking empty input elds, identifying valid email address, veri cation of password constraints etc.
Client side form validation also helps in providing better user interactivity with the website, while deep
veri cation or validation of input data is being done at Server-side.

http://www.c-sharpcorner.com/article/asp-net-mvc5-jquery-form-validator/ 1/13
8/13/2017 ASP.NET MVC 5 - JQuery Form Validator

Server-Side Form Validation

Server side form validation, as the name suggests, is done on the Server side of the web which involves
Ask a Question
deep validation and veri cation on user input data, e.g. identi cation of valid user account etc.

Today, I shall be demonstrating the integration of jQuery based Client-side Validator with ASP.NET MVC5
platform. Although, MVC 5 platform already facilitates client side validation as a built-in component, yet
the built-in client side validator component is not very user attractive or rich in nature.

Following are some prerequisites before you proceed further in this article.

1. Knowledge of ASP.NET MVC5.


2. Knowledge of HTML.
3. Knowledge of JavaScript.
4. Knowledge of Bootstrap.
5. Knowledge of Jquery.
6. Knowledge of C# Programming.

You can download the complete source code for this article or you can follow the step by step discussion
below. The sample code is being developed in Microsoft Visual Studio 2015 Enterprise.

Now, let’s begin.

Create a new MVC web project and name it as "JqueryFormValidator".

Make sure that you have installed the following two JavaScripts into your "Scripts" folder i.e.

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

Now, open "RouteCon g.cs" le and replace the following code in it i.e.

01. using System;


02. using System.Collections.Generic;
03. using System.Linq;
04. using System.Web;
05. using System.Web.Mvc;
06. using System.Web.Routing;
07.
08. namespace JqueryFormValidator

http://www.c-sharpcorner.com/article/asp-net-mvc5-jquery-form-validator/ 2/13
8/13/2017 ASP.NET MVC 5 - JQuery Form Validator
09. {
10. public class RouteConfig
11. {
12. public static void RegisterRoutes(RouteCollection routes)
13. { Ask a Question
14. routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
15.
16. routes.MapRoute(
17. name: "Default",
18. url: "{controller}/{action}/{id}",
19. defaults: new { controller = "Home", action = "Register", id = UrlParameter.Optional }
20. );
21. }
22. }
23. }

In the above code, I have simply changed my default launch action from "Index" to "Register".

Now, open "BundleCon g.cs" le and replace it with the following code.

01. using System.Web;


02. using System.Web.Optimization;
03.
04. namespace JqueryFormValidator
05. {
06. public class BundleConfig
07. {
08. // For more information on bundling, visit http://go.microsoft.com/fwlink/?
LinkId=301862
09. public static void RegisterBundles(BundleCollection bundles)
10. {
11. bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
12. "~/Scripts/jquery-{version}.js"));
13.
14. bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
15. "~/Scripts/jquery.validate.js",
16. "~/Scripts/jquery.validate.unobtrusive.js"));
17.
18. // Use the development version of Modernizr to develop with and learn from. Then, when you'r
19. // ready for production, use the build tool at http://modernizr.com to pick only the tests y
20. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
21. "~/Scripts/modernizr-*"));
22.
23. bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
24. "~/Scripts/bootstrap.js",
25. "~/Scripts/respond.js"));
26.
27. // JQuery validator.
28. bundles.Add(new ScriptBundle("~/bundles/custom-validator").Include(
29. "~/Scripts/script-custom-validator.js"));
30.
31. bundles.Add(new StyleBundle("~/Content/css").Include(
32. "~/Content/bootstrap.css",
33. "~/Content/site.css"));
34. }
35. }
36. }

In the above code, I have added my "jquery.validate.js", "jquery.validate.unobtrusive.js" & "script-custom-


validator.js" scripts as a bundle, which are required for jQuery form validation. Following lines of code are
added in above code.

01. bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(


02. "~/Scripts/jquery.validate.js",
03. "~/Scripts/jquery.validate.unobtrusive.js"));
04.
05.
06. bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(

http://www.c-sharpcorner.com/article/asp-net-mvc5-jquery-form-validator/ 3/13
8/13/2017 ASP.NET MVC 5 - JQuery Form Validator
07. "~/Scripts/bootstrap.js",
08. "~/Scripts/respond.js"));

Create a new Controller class in "Controllers" folder andAsk


name it "HomeController.cs". Replace the
a Question
following code in "HomeController.cs" le.

01. using JqueryFormValidator.Models;


02. using Microsoft.AspNet.Identity;
03. using System;
04. using System.Collections.Generic;
05. using System.Linq;
06. using System.Web;
07. using System.Web.Mvc;
08.
09. namespace JqueryFormValidator.Controllers
10. {
11. public class HomeController : Controller
12. {
13. #region Register
14.
15. //
16. // GET: /Home/Register
17. [AllowAnonymous]
18. public ActionResult Register()
19. {
20. return View();
21. }
22.
23. //
24. // POST: /Home/Register
25. [HttpPost]
26. [AllowAnonymous]
27. [ValidateAntiForgeryToken]
28. public ActionResult Register(RegisterViewModel model)
29. {
30. if (ModelState.IsValid)
31. {
32. // Info.
33. Console.WriteLine(model.Email);
34. }
35.
36. // If we got this far, something failed, redisplay form
37. return View(model);
38. }
39.
40. #endregion
41. }
42. }

In the above code. I have simply created "Register" method for both, HTTP Get and HTTP Post methods.
Both methods are doing nothing but just validating my form input's basic constraints de ned in View
Model.

Now, create a new View Model class in "Models" folder and name it "HomeViewModels.cs". Replace the
following piece of code in the "HomeViewModels.cs" le.

01. using System.Collections.Generic;


02. using System.ComponentModel.DataAnnotations;
03.
04. namespace JqueryFormValidator.Models
05. {
06. public class RegisterViewModel
07. {
08. [Required]
09. [EmailAddress]
10. [Display(Name = "Email")]
11. public string Email { get; set; }
12.
13. [Required]

http://www.c-sharpcorner.com/article/asp-net-mvc5-jquery-form-validator/ 4/13
8/13/2017 ASP.NET MVC 5 - JQuery Form Validator
14. [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength
15. [DataType(DataType.Password)]
16. [Display(Name = "Password")]
17. public string Password { get; set; }
18. Ask a Question
19. [DataType(DataType.Password)]
20. [Display(Name = "Confirm password")]
21. [Compare("Password", ErrorMessage = "The password and confirmation password do not match."
22. public string ConfirmPassword { get; set; }
23. }
24. }

In the above code, I have created my View Model for my "Register" UI i.e. "RegisterViewModel" and
created three properties in it along with basic validations on those properties. For Email property, I have
de ned required attribute constraint and email constraint. This will help MVC 5 platform to identify any
invalid basic input from end-user.

Now, open "_Layout.cshtml" le from "Shared" folder and replace the code with following.

01. <!DOCTYPE html>


02. <html>
03. <head>
04. <meta charset="utf-8" />
05. <meta name="viewport" content="width=device-width, initial-scale=1.0">
06. <title>@ViewBag.Title</title>
07. @Styles.Render("~/Content/css")
08. @Scripts.Render("~/bundles/modernizr")
09.
10. <!-- Font Awesome -->
11. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-
awesome.min.css" />
12.
13. </head>
14. <body>
15. <div class="navbar navbar-inverse navbar-fixed-top">
16. <div class="container">
17. <div class="navbar-header">
18. <button type="button" class="navbar-toggle" data-toggle="collapse" data-
target=".navbar-collapse">
19. <span class="icon-bar"></span>
In Focus
20. <span class="icon-bar"></span>  
201721.
First Half of the Year MVPs Announced
<span class="icon-bar"></span>
22. </button>
23.
24.
</div>
</div>
Contribute
25. </div>
26. <div class="container body-content">
27. @RenderBody()
28. <hr />
29. <footer>
30. <center>
31. <p>
<strong>Copyright © @DateTime.Now.Year - <a href="http://www.asmak9.com/">Asma's Blog</a>.
</strong> All rights reserved.</p>
32. </center>
33. </footer>
34. </div>
35.
36. @Scripts.Render("~/bundles/jquery")
37. @Scripts.Render("~/bundles/bootstrap")
38.
39. @RenderSection("scripts", required: false)
40. </body>
41. </html>

In the above code, I have simply created my basic default layout for all pages.

Let's create our "Register.cshtml" View in "Views/Home" folder and place the following code in it

http://www.c-sharpcorner.com/article/asp-net-mvc5-jquery-form-validator/ 5/13
8/13/2017 ASP.NET MVC 5 - JQuery Form Validator

01. @model JqueryFormValidator.Models.RegisterViewModel


02. @{
03. ViewBag.Title = "Register";
04. }
05. Ask a Question
06. <h2>@ViewBag.Title.</h2>
07.
08. @using (Html.BeginForm("Register", "Home", FormMethod.Post, new { @id = "registerFormId", @class
horizontal", role = "form" }))
09. {
10. @Html.AntiForgeryToken()
11. HtmlHelper.UnobtrusiveJavaScriptEnabled = false;
12.
13. <h4>Create a new account.</h4>
14. <hr />
15.
16. <div class="form-group">
17. @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
18. <div class="col-md-10">
19. @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
20. @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger " })
21. </div>
22.
23. </div>
24. <div class="form-group">
25. @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
26. <div class="col-md-10">
27. @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
28. @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-
danger " })
29. </div>
30.
31. </div>
32. <div class="form-group">
33. @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
34. <div class="col-md-10">
35. @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
36. @Html.ValidationMessageFor(m => m.ConfirmPassword, "", new { @class = "text-
danger " })
37. </div>
38. </div>
39. <div class="form-group">
40. <div class="col-md-offset-2 col-md-10">
41. <input type="submit" class="btn btn-default" value="Register" />
42. </div>
43. </div>
44. }
45.
46. @section Scripts {
47. @Scripts.Render("~/bundles/jqueryval")
48. @Scripts.Render("~/bundles/custom-validator")
49. }

In the above code, I have attached my View Model "RegisterViewModel" with my "Register" UI. In the
above code, notice the following line of code.

01. HtmlHelper.UnobtrusiveJavaScriptEnabled = false;

Change the above property value to true and execute the project followed by a click on "Register" button,
without providing any input. You will see the following error messages.

http://www.c-sharpcorner.com/article/asp-net-mvc5-jquery-form-validator/ 6/13
8/13/2017 ASP.NET MVC 5 - JQuery Form Validator

Ask a Question

The above images show default client-side validation response of ASP.NET MVC5. Let's change it to that
of jQquery form validation instead.

Change "HtmlHelper.UnobtrusiveJavaScriptEnabled" value back to True and create new le in "Scripts"


folder  naming it "script-custom-validator.js". Place the following code in it.

01. $(document).ready(function ()
02. {
03. $('#registerFormId').validate({
04. errorClass: 'help-block animation-
slideDown', // You can change the animation class for a different entrance animation - check animations
05. errorElement: 'div',
06. errorPlacement: function (error, e) {
07. e.parents('.form-group > div').append(error);
08. },
09. highlight: function (e) {
10.
11. $(e).closest('.form-group').removeClass('has-success has-error').addClass('has-
error');
12. $(e).closest('.help-block').remove();

http://www.c-sharpcorner.com/article/asp-net-mvc5-jquery-form-validator/ 7/13
8/13/2017 ASP.NET MVC 5 - JQuery Form Validator
13. },
14. success: function (e) {
15. e.closest('.form-group').removeClass('has-success has-error');
16. e.closest('.help-block').remove();
17. }, Ask a Question
18. rules: {
19. 'Email': {
20. required: true,
21. email: true
22. },
23.
24. 'Password': {
25. required: true,
26. minlength: 6
27. },
28.
29. 'ConfirmPassword': {
30. required: true,
31. equalTo: '#Password'
32. }
33. },
34. messages: {
35. 'Email': 'Please enter valid email address',
36.
37. 'Password': {
38. required: 'Please provide a password',
39. minlength: 'Your password must be at least 6 characters long'
40. },
41.
42. 'ConfirmPassword': {
43. required: 'Please provide a password',
44. minlength: 'Your password must be at least 6 characters long',
45. equalTo: 'Please enter the same password as above'
46. }
47. }
48. });
49. });

In the above code, I have de ned validation con guration for jQuery form validation. Let's dissect the
code chunk by chunk i.e.

01. $('#registerFormId').validate({
02. errorClass: 'help-block animation-
slideDown', // You can change the animation class for a different entrance animation - check animations
03. errorElement: 'div',
04. errorPlacement: function (error, e) {
05. e.parents('.form-group > div').append(error);
06. },
07. highlight: function (e) {
08.
09. $(e).closest('.form-group').removeClass('has-success has-error').addClass('has-
error');
10. $(e).closest('.help-block').remove();
11. },
12. success: function (e) {
13. e.closest('.form-group').removeClass('has-success has-error');
14. e.closest('.help-block').remove();
15. },

The above piece of code attaches my account register form with jQuery form validator by using form ID.
Then, I have de ned settings about where to place the error message and its related styling. I have also
de ned methods for validator that describe what happens when error message is highlighted and form
validation is successful.

01. rules: {
02. 'Email': {
03. required: true,
04. email: true

http://www.c-sharpcorner.com/article/asp-net-mvc5-jquery-form-validator/ 8/13
8/13/2017 ASP.NET MVC 5 - JQuery Form Validator
05. },
06.
07. 'Password': {
08. required: true,
09. minlength: 6 Ask a Question
10. },
11.
12. 'ConfirmPassword': {
13. required: true,
14. equalTo: '#Password'
15. }
16. },
17. messages: {
18. 'Email': 'Please enter valid email address',
19.
20. 'Password': {
21. required: 'Please provide a password',
22. minlength: 'Your password must be at least 6 characters long'
23. },
24.
25. 'ConfirmPassword': {
26. required: 'Please provide a password',
27. minlength: 'Your password must be at least 6 characters long',
28. equalTo: 'Please enter the same password as above'
29. }
30. }

The above piece of code will de ne our form validation rules and error messages for each input on form.
Notice that in the above code that in the rules & messages section, the keyword "Email" is actually the
"name" property of input tag that our Razor View Engine automatically generates based on our attached
View Model.

Finally, execute the project and click the "Register" button without providing the input data, and you will
see the jQuery form validation errors in action, as shown below.

http://www.c-sharpcorner.com/article/asp-net-mvc5-jquery-form-validator/ 9/13
8/13/2017 ASP.NET MVC 5 - JQuery Form Validator

Ask a Question

Before I end this tutorial, let's talk about the following properties in "web.con g" le.

01. <add key="ClientValidationEnabled" value="true" />


02. <add key="UnobtrusiveJavaScriptEnabled" value="true" />

The above properties are set True by default which means MVC 5 platform ensures that client side
validation on form validation is on. For jQuery form validation to work, we set
"HtmlHelper.UnobtrusiveJavaScriptEnabled = false;" property false in the register form instead of
"web.con g" le; this means if we set the value false for above property in "web.con g" le, then we will
disable client side validation across application.Thus, the preferred practice is to disable the property into
the form in which you want to use jQuery form validation.

Conclusion

http://www.c-sharpcorner.com/article/asp-net-mvc5-jquery-form-validator/ 10/13
8/13/2017 ASP.NET MVC 5 - JQuery Form Validator

In this article, you have learned about jQuery form validator, how to use it with ASP.NET MVC 5, how to
con gure it, how to stop MVC 5 platform client side validation, and how to implement jQuery form
validator to your form.
Ask a Question
Download 100% FREE Spire O ce APIs

ASP.NET Form Validator jQuery MVC 5

Asma Khalid

Computer Programmer by Profession, Computer Scientist by Heart, Fanatic Explorer,


Technology Centric. I am a Versatile Computer Science Evangelist. Enjoy doodling with
technology.
http://www.asmak9.com/

361 650.4k 1 1

6 2

Type your comment here and press Enter Key (Minimum 18 characters)

Thank you good work


Nader Kamal Jul 10, 2017
1456 2 121 0 0 Reply

Nice explanation asma


yashwanth kumar Jul 07, 2017
1450 8 0 0 0 Reply

Comment Using

0 Comments Sort by Oldest

Add a comment...

Facebook Comments Plugin

File APIs for .NET


Aspose are the market leader of .NET APIs for le business formats – natively work with
DOCX, XLSX, PPT, PDF, MSG, MPP, images formats and many more!

http://www.c-sharpcorner.com/article/asp-net-mvc5-jquery-form-validator/ 11/13
8/13/2017 ASP.NET MVC 5 - JQuery Form Validator

Ask a Question

TRENDING UP

01 Multithreading In C# .Net

02 Best Practices For MVC

03 What Is Big Data?

04 Making Web Sites Look Like Native Apps Without the App Store

05 How To Use Joins, and Group By Clause In Entity Framework With LINQ C#

06 Confessions Of An Angry Programmer

07 Creating Web API With ASP.NET Core Using Visual Studio Code

08 Future Of IoT, Machine Learning, And Arti cial Intelligence

09 Project Server 2013 Migration From One Farm To Another

10 Learn MVC : Using Angular PDF File Viewer


View All

Follow @csharpcorner

C# Corner
1,282,541 likes

Like Page Learn More

Be the first of your friends to like this

http://www.c-sharpcorner.com/article/asp-net-mvc5-jquery-form-validator/ 12/13
8/13/2017 ASP.NET MVC 5 - JQuery Form Validator

Ask a Question

Philadelphia
New York
London
Delhi

Join C# Corner
A community of 2.3 million developers worldwide

Enter your email address Sign Up

Learn ASP.NET MVC Learn ASP.NET Core Learn Python Learn JavaScript Learn Xamarin
Learn Oracle More...
Home Events Consultants Jobs Career Advice Stories

About Us Contact Us Privacy Policy Terms Media Kit Sitemap Report a Bug FAQ
©2017 C# Corner. All contents are copyright of their authors.

http://www.c-sharpcorner.com/article/asp-net-mvc5-jquery-form-validator/ 13/13

You might also like