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.
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:
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.
Now we have explicitly defined all of the data fields that are required for the user to enter. On to 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.
This will return an empty View if there was a problem validating any of the fields.
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.
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.