Client Side Validation in ASP.NET MVC

Firstly, you just need to create an ASP.NET MVC application. To create a new ASP.NET MVC application, Open Visual Studio choose File, New, then Project.

new project

It will open a New Project window, from where you need to choose node Visual C# and then Web and from the right pane you need to choose ASP.NET Web Application. Name the application.

ASP.NET Web Application

It will open new window from where you can choose different type of the ASP.NET MVC project template. You need to choose MVC and click OK.

mvc

It will create a ASP.NET MVC application. When you open the Web.Config file, you can see there are two options by default [If you are working with MVC3 or MVC2, Please see it should be there]. These are ClientValidationEnabled and UnobtrusiveJavaScriptEnabled. And these should be true for client side validation.

add key

Here I am going to use Data Annotation which is widely used by developers because there is no need to write extra code for validation. All are written predefined.

Create a ViewModel for posting some blog data.

PostViewModel.cs

  1. using ClientSideValidationDemo.Data.Entities;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.ComponentModel.DataAnnotations;  
  5. using System.Linq;  
  6. using System.Web;  
  7. using System.Web.Mvc;  
  8.   
  9. namespace ClientSideValidationDemo.Data.ViewModel  
  10. {  
  11.     public class PostViewModel  
  12.     {  
  13.         public int PostId { getset; }  
  14.   
  15.         [Display(Name="Post Title")]  
  16.         [Required(ErrorMessage="Post Title is required")]  
  17.         [RegularExpression(@"^.{5,}$", ErrorMessage = "Minimum 3 characters required")]  
  18.         [StringLength(500,MinimumLength=3, ErrorMessage="Invalid Title Lenght")]  
  19.         public string PostTitle { getset; }  
  20.   
  21.   
  22.         [MaxLength(Int32.MaxValue, ErrorMessage = "More than max value")]  
  23.         [AllowHtml]          
  24.         [Display(Name = "Short Content")]  
  25.         [Required(ErrorMessage = "Short Content is required")]          
  26.         public string ShortPostContent { getset; }  
  27.   
  28.         [AllowHtml]  
  29.         [MaxLength(Int32.MaxValue, ErrorMessage = "More than max value")]  
  30.         [Display(Name = "Full Content")]  
  31.         [Required(ErrorMessage = "Full Content is required")]      
  32.         public string FullPostContent { getset; }  
  33.   
  34.         [Display(Name = "Meta keywords")]          
  35.         public string MetaKeywords { getset; }  
  36.   
  37.         [Display(Name = "Meta Description")]  
  38.         public string MetaDescription { getset; }  
  39.      
  40.   
  41.         [Required(ErrorMessage="Category is required")]  
  42.         public int SelectValue  
  43.         {  
  44.             get;  
  45.             set;  
  46.               
  47.         }  
  48.         public virtual Category postCategory { getset; }  
  49.   
  50.         [Display(Name="Post Category")]          
  51.           
  52.         public virtual List<Category> PostCategories { getset; }  
  53.         public List<Tag> PostTags { getset; }  
  54. }  
  55.   
  56.         [Required(ErrorMessage="Tag is required")]  
  57.         public string hdnTagList { getset; }  
  58.   
  59.         public virtual int CategoryId { getset; }  
  60.         
  61.   
  62.           
  63.         public string PostUrl { getset; }  
  64.   
  65.         public User userDetails { getset; }  
  66.   
  67.         public int NumberOfLikes { getset; }  
  68.   
  69.         public int NumberOfComments { getset; }  
  70.   
  71.         public int postPageStatus { getset; }  
  72.   
  73.         public string CategoryName { getset; }  
  74.   
  75.           
  76.   
  77.     }  
  78. }  
postController.cs
  1. [HttpPost]  
  2. public ActionResult AddNewPost(PostViewModel model)  
  3. {  
  4.   
  5.     if (ModelState.IsValid)  
  6.     {  
  7.         int varEntityType = 1;  
  8.         if (PostType.post.Equals("page"))  
  9.         {  
  10.             varEntityType = 2;  
  11.         }  
  12.         var category = _postRepository.GetCategoryList(model.SelectValue);  
  13.         var postUrl = string.Empty;  
  14.         var shortContent = string.Empty;  
  15.         if (model.PostUrl != null)  
  16.         {  
  17.             postUrl = model.PostUrl.ToSeoUrl();  
  18.         }  
  19.         else  
  20.         {  
  21.             postUrl = model.PostTitle.ToSeoUrl();  
  22.         }  
  23.         if (String.IsNullOrEmpty(model.ShortPostContent))  
  24.         {  
  25.             if (model.FullPostContent.Length > 1000)  
  26.             {  
  27.                 shortContent = model.FullPostContent.Substring(0, 1000);  
  28.             }  
  29.             else  
  30.             {  
  31.                 shortContent = model.FullPostContent;  
  32.             }  
  33.         }  
  34.         else  
  35.         {  
  36.             shortContent = model.ShortPostContent;  
  37.         }  
  38.         var postEntity = new Post  
  39.         {  
  40.             PostTitle = model.PostTitle,  
  41.             MetaKeywords = model.MetaKeywords,  
  42.             MetaDescription = model.MetaDescription,  
  43.             ShortPostContent = shortContent,  
  44.             FullPostContent = model.FullPostContent,  
  45.             PostAddedDate = DateTime.Now,  
  46.             EntityType = varEntityType,  
  47.             PostUpdatedDate = DateTime.Now,  
  48.             Categories = category,  
  49.             PostUrl=postUrl,  
  50.             UserId=LoggedUser.UserId,  
  51.         };  
  52.         int postId = Convert.ToInt32(_postRepository.AddNewPost(postEntity));  
  53.         if (postId > 0)  
  54.         {  
  55.               
  56.                     TempData["Success"] = "New Post Added Successfully!";  
  57.                     return RedirectToAction("AddNewPost""Post");  
  58.                   
  59.             }  
  60.         }  
  61.   
  62.     }  
  63.     model.PostCategories = _categoryRepository.GetCategoryList();  
  64.     ViewBag.Failed = "Filled Required content!";  
  65.     return View(model);  
  66. }  
AddNewPost.cshtml
  1. @model ClientSideValidationDemo.Data.ViewModel.PostViewModel  
  2.   
  3. @{  
  4.     ViewBag.Title = "Add New Blog";  
  5.     Layout = "~/Areas/Blog/Views/Shared/_LayoutMain.cshtml";  
  6. }  
  7.   
  8. <div class="span9">  
  9.     @using (Html.BeginForm("AddNewPost""Post", FormMethod.Post, new { enctype = "multipart/form-data" }))  
  10.     {  
  11.   
  12.         <div class="widget ">  
  13.             <div class="widget-header"><i class="icon-user"></i><h3>Submit Post</h3></div><div class="widget-content">  
  14.   
  15.                 @if (TempData["Success"] != null)  
  16.                 {  
  17.                     <p class="alert alert-success" id="successMessageAddPost">@TempData["Success"]</p>  
  18.                 }  
  19.                 @if (ViewBag.Failed != null)  
  20.                 {  
  21.                     <p class="alert" id="failedMessageAddPost">@ViewBag.Failed</p>  
  22.                 }  
  23.   
  24.   
  25.                 <div class="form-horizontal">  
  26.                     <div class="control-group">  
  27.                         <label class="control-label">@Html.LabelFor(m => m.PostCategories)</label><div class="controls">  
  28.                             @Html.DropDownListFor(m => m.SelectValue, new SelectList(Model.PostCategories, "CategoryId""CategoryName"), "Please select category"new { @class = "btn-group open" })  
  29.                             <br />  
  30.                             @Html.ValidationMessageFor(m => m.SelectValue, ""new { @class = "validation_error" })  
  31.   
  32.                         </div>  
  33.                     </div><div class="control-group">  
  34.                         <label class="control-label">@Html.LabelFor(m => m.PostTitle)</label><div class="controls">  
  35.                             @Html.TextBoxFor(m => m.PostTitle, new { @class = "span6" })  
  36.                             <br />  
  37.                             @Html.ValidationMessageFor(m => m.PostTitle, ""new { @class = "validation_error" })  
  38.   
  39.   
  40.   
  41.                         </div>  
  42.                     </div><div class="control-group">  
  43.                         <label class="control-label">Tags  @Html.HiddenFor(m => m.hdnTagList)</label><div class="controls">  
  44.                             <input type="text" id="txtAddNewTag" class="inputBoxMedium" /><input type="button" id="btnAddTag" class="btn btn-primary" value="Add" title="add new tag" /><input type='button' id='btnRemoveTag' class="btn btn-danger" value="Remove" title="remove tag" />  
  45.                             @Html.ValidationMessageFor(m => m.hdnTagList, ""new { @class = "validation_error" })  
  46.                             <br /><br /><span id="TextBoxesGroup"></span>  
  47.                         </div>  
  48.                     </div><div class="tabbable">  
  49.                         <ul class="nav nav-tabs"><li class="active"><a href="#formcontrols" data-toggle="tab">Content</a></li><li><a href="#jscontrols" data-toggle="tab">Options</a></li></ul><br><div class="tab-content">  
  50.                             <div class="tab-pane active" id="formcontrols">  
  51.                                 <div class="form-horizontal">  
  52.                                     <div>  
  53.                                         <b>Short Content</b>  
  54.                                         @if (Request.Browser.IsMobileDevice)  
  55.                                         {  
  56.                                             <script src="//tinymce.cachefly.net/4.1/tinymce.min.js"></script>  
  57.                                             <script>tinymce.init({selector: 'textarea', editor_selector: "ShortPostContent"});</script>  
  58.                                         }  
  59.                                         else  
  60.                                         {  
  61.   
  62.                                             <script src="http://cdn.ckeditor.com/4.4.6/full-all/ckeditor.js"></script>  
  63.                                         }  
  64.                                         @Html.TextAreaFor(m => m.ShortPostContent, new { @id = "ShortPostContent", @rows = 2, @cols = 2 })  
  65.                                         <br />  
  66.                                         @Html.ValidationMessageFor(m => m.ShortPostContent, ""new { @class = "validation_error" })  
  67.                                     </div><div>  
  68.                                         <b>Full Content</b>  
  69.                                         @if (Request.Browser.IsMobileDevice)  
  70.                                         {  
  71.                                             <script src="//tinymce.cachefly.net/4.1/tinymce.min.js"></script>  
  72.                                             <script>tinymce.init({selector: 'textarea', editor_selector: "FullPostContent"});</script>  
  73.                                         }  
  74.                                         else  
  75.                                         {  
  76.                                             <script src="http://cdn.ckeditor.com/4.4.6/full-all/ckeditor.js"></script>  
  77.                                         }  
  78.                                         @Html.TextAreaFor(m => m.FullPostContent, new { @id = "FullPostContent" })  
  79.                                         <input type="hidden" id="hdnCodeStyle" value="" /><br />  
  80.                                         @Html.ValidationMessageFor(m => m.FullPostContent, ""new { @class = "validation_error" })  
  81.                                     </div>  
  82.                                 </div><br />  
  83.                             </div><div class="tab-pane" id="jscontrols">  
  84.                                 <div class="form-horizontal">  
  85.                                     <div class="control-group">  
  86.                                         <label class="control-label">@Html.LabelFor(m => m.PostUrl)</label><div class="controls">  
  87.                                             @Html.TextBoxFor(m => m.PostUrl, new { @class = "span6" })  
  88.                                             <br />  
  89.                                             @Html.ValidationMessageFor(m => m.PostUrl, ""new { @class = "validation_error" })  
  90.                                         </div>  
  91.                                     </div><div class="control-group">  
  92.                                         <label class="control-label">@Html.LabelFor(m => m.MetaKeywords)</label><div class="controls">  
  93.                                             @Html.TextAreaFor(m => m.MetaKeywords, new {@class = "span6", @rows = 3, @cols = 2 })                                              
  94.                                             <br />  
  95.                                             @Html.ValidationMessageFor(m => m.MetaKeywords, ""new { @class = "validation_error" })  
  96.                                         </div>  
  97.                                     </div><div class="control-group">  
  98.                                         <label class="control-label">@Html.LabelFor(m => m.MetaDescription)</label><div class="controls">  
  99.                                            @Html.TextAreaFor(m => m.MetaDescription, new { @class = "span6", @rows = 3, @cols = 2 })  
  100.                                             <br />  
  101.                                             @Html.ValidationMessageFor(m => m.MetaDescription, ""new { @class = "validation_error" })  
  102.                                         </div>  
  103.                                     </div>  
  104.                                 </div>  
  105.                             </div>  
  106.                         </div>  
  107.                     </div>  
  108. <div style="text-align: center;"><input type="submit" value="Publish" id="btnAddNewPost" class="btn btn-success" /><input type="submit" value="Preview" id="btnPreview" class="btn btn-warning" /></div></div></div><br /><div><span>@ViewBag.Message</span></div>  
  109.                 </div>  
  110.             </div>  
  111.         </div>  
  112.     }  
  113. </div>  
When you click on the Publish button without filling the require data, it will not show error message below the control rather than loading the whole page.

control

Submit post

Please make sure, you are referring the validating jQuery script file with your view or corresponding layout page.

layout page

Thanks for reading this article, hope you enjoyed it.