Validating Input with ASP .NET MVC 2

There aren't many web applications that do not accept user input of some sort. That being said, you inevitably have to trust the user to actually do something in order for your application to do interesting things.

The problem is, what if the user enters something you don't expect them to? This can lead to all sorts of unexpected behaviors from a simple error to a full-blown attack on your site.

Luckily, the .NET framework makes it easy to add validation to your MVC project.

The code I'm using here is for one of my open source projects called LoanGeek. The source code is also available on Github.

The Model

In the model, we have the main class that is going to hold all of the information about a particular mortgage loan. The model is a great place to define what members we want to validate since this is where we define the structure behind our application.

Without validation, we might have something that looks similar to this:

namespace LoanGeek.Models {
  public class LoanData {
    public double Principal { get; set; }
    public double Interestate { get; set; }
    public int LoanTerm { get; set; }
    ...
    ...
  }
}

Now, all we have to do is take our existing model, find the members that we want the user to input, and make sure we add validation for each member. This can be done by using declarative attributes.

namespace LoanGeek.Models {
  public class LoanData {

    [Required(ErrorMessage = "Please enter your the total loan amount.")]
    public double Principal { get; set; }

    [Required(ErrorMessage = "Please enter the interest rate.")]
    public double Interestate { get; set; }

    [Required(ErrorMessage = "Please enter the number of years of the loan.")]
    public int LoanTerm { get; set; }
    ...
    ...
  }
}

Now we have explicitly defined all of the data fields that are required for the user to enter. On to the Controller!

The Controller

Once the user clicks submit the ModelState will attempt to validate before the View is loaded again. Here, we can check to see if the user inputed valid data into our application and handle the result accordingly.

[HttpPost]
public ActionResult Index(LoanData loanData) {
  if (ModelState.IsValid) {
    return View("Index", loanData);
  } else {
    return View();
  }
}

This will return an empty View if there was a problem validating any of the fields.

The View

Finally, where the rubber meets the road. In the View, we simply need to output the validation summary and let the framework do the rest.

<% using (Html.BeginForm()) { %>
  <%: Html.ValidationSummary() %>
  ...
  ...
<% } %>

Once we have this final bit in place, our application is protected against incorrect user input. As an added bonus, the framework will also validate against the different datatypes in your model and display an error when invalid characters are entered.

So there you have it. A simple way to validate user input in ASP .NET MVC 2.

Creative Commons License

What do you think?