Monday, 21 October 2013

Understanding data validation in Asp.net Mvc

One of the golden rule for web developers is "Never ever trust user data", this rule is very vital because user data can contain all sorts of virus and bacteria that will infect and hinder the normal functioning of your application. Data validation is also a way to ensure that user data is formatted according to your applications' specification (like requiring a particular date or string format).

You may be may confused about when to validate and when not to do validation. In response,  validation should be done on every data that will be saved to the database, data used for querying such as data from the search bar or data that will be worked on by your application.

Validation in Asp.net Mvc is actually very simple and does not require you to write custom validation code except when you have a special requirement that is not covered in the canned validator attributes. To do validation simply involves attaching attributes to the properties of your model classes as shown below

public class Login
{        
          [Required(ErrorMessage = "Enter your username")]
          public string Username{get; set;}

          [Required(ErrorMessage = "Enter your password")]
          public string Password{get; set;}



In the above class, the properties are tacked with the required attribute which contains an error message to display to the user if validation fails. Now this required attribute forces the user to provide a value for each of the properties, in this case the username and password respectively.

When the data for the above model is submitted to an action method like Login in Account controller, the validation is checked by using IsValid property of the ModelState class in System.Web.Mvc as shown below

public ActionResult Login(Login model)
{
    if(ModelState.IsValid)
    {
          //Process and save the data to data store
          // either return the same view with an empty textboxes or
         // redirect the user to another action method
    }

 //return the view to the user with the invalid data
return View(model);
}

if our model has an empty property, then it will not validate. It will be returned to the user together with our error message for that particular property(s).

This about sums it up for validation  in asp.net mvc 4, from the few lines of code that we have written, we can see that it is actually very simple to do validation in mvc.

No comments:

Post a Comment