How to Do Client Side Validation in ASP.NET MVC 2?

July 23, 2010 · 2 comments

in Ajax,ASP.NET MVC

One way of providing good user experience and saving some redundant ‘server side processing’ and ‘bandwidth’ is to use client side validation on the UI. ASP.NET MVC 2 provides for this facility out of the box via the use of **Data Annotations, javascripts and html helpers**. For example say you have an entity Post in your blog application. The recommended ASP.NET MVC 2 approach is to decorate your entity with validation attributes. So for our Post entity we would do the following, assuming you are using Code First Entity Framework 4.0 CTP 4, nHibernate or similar ORM tool.

    
    using System.ComponentModel.DataAnnotations;
    
    public class Post
    {
        [Required(ErrorMessage = "Title is required.")]
        public string Title {get;set;}
        
        [Required(ErrorMessage = "Body is required.")]
        public string Body {get;set;}
    }

If you are generating your entities using EF4.0 designer tools or similar then you will need to decorate your partial classes, like so.

    [MetadataType(typeof(PostMetadata))]
    public partial class Post
    {  
    }

    public class PostMetadata
    {
        [Required(ErrorMessage = "Title is required.")]
        public string Title {get;set;}
        
        [Required(ErrorMessage = "Body is required.")]
        public string Body {get;set;}
    }

Then in your ‘view’ you include the required validation javascript files – assuming you have the standard `Scripts` folder that ASP.NET MVC provides for – as follows.

    <script src="/Scripts/MicrosoftAjax.js" type="text/javascript" />
    <script src="/Scripts/MicrosoftMvcValidation.js" type="text/javascript" />

Additionally, you need to include the following call in your view, like so,

    <% Html.EnableClientValidation(); %>
    ..... //Some view codes here
The validation now happens both in the client side via javascript/ajax and also in the server side.

  • Cahya Darma

    Hello. I generate the data model from my database. How can I do the validation similar with your approach, server side or client side? Thank you very much.

    • Bikal Gurung

      In ASP.NET MVC, once data annotation validation attributes are applied on data models, the framework can do validation for you both on the client side and the server side. On the server side validation is done for you by ASP.NET MVC before data is passed to Controller action methods. You need to call ModelState.IsValid to check if the incoming data is valid. So for our model – Post – above, say we want to save the edits done on it, then we would do the following in the PostController action method.

          public class PostController : Controller
          {
              //Other actions methods here.    
              [HttpPost]
              public ActionResult Edit(Post post)
              {
                  if(ModelState.IsValid)
                  {
                      //Save our Post model      
                      Redirect("/");
                  }   
                  //We have validation errors so display those. The method below does that.
                  return View(post);
              }
          }
      

Previous post:

Next post: