Professional Documents
Culture Documents
ASP MVC Validations
ASP MVC Validations
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.
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, 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.
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.
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.
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.
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"));
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.
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.
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
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.
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.
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.
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
Asma Khalid
361 650.4k 1 1
6 2
Type your comment here and press Enter Key (Minimum 18 characters)
Comment Using
Add a comment...
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
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#
07 Creating Web API With ASP.NET Core Using Visual Studio Code
Follow @csharpcorner
C# Corner
1,282,541 likes
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
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