Overview of MVC Model Validation
Model validation is critical. Properly implemented your validation rules become an application level firewall controlling access to your database or business logic. The importance of validating input cannot be overstated.
Fortunately, MVC allows you to validate input with almost no effort.
Here David steps you through the mechanics of setting up a model to be validated. He starts with a simple Model, creates a view using the TemplateHelpers that we have seen earlier. This time, we see a couple of new helpers Html.ValidationSummary and Html.ValidationMessageFor. These are used to display any validation messages that are added to the model.
He then returns to the Model and starts adding attributes to the properties. He showcases, Required, StringLength, and RegularExpression. Any validation attribute derived from System.ComponentModel.DataAnnotations.ValidationAttribute can be used.
Explicitly Validating a Model
Getting Started with Validation [HowMVCWorks]
Using the attributes that we saw in the previous section is the easiest way to go. They can automatically be implemented and will generally work with no intervention on the part of the developer beyond adding the appropriate attributes.
Sometimes you need something more custom. Suppose you want to add a validation message that the required ID was not found in the database. Or you might want to add a validation where the message cannot be determined at design time and needs run time data. You may also have a custom test based on more than one property.
In this article, Eric steps through the mechanics of Manual Validation. Instead of relying on the framework to cycle through the attributes on your properties, you explicitly write code to implement your test and then explicitly call ModelState.AddModelError.
public ActionResult CreateANewMonkey(MonkeyViewModel vm)
ModelState.AddModelError("MonkeyName", "Please enter a name.");
if (vm.Age > 50)
ModelState.AddModelError("Age", "The age of the monkey cannot be greater than 50.");
Now when you return the user to the View, it will highlight the input fields that had problems
Displaying Validation Messages
We have already seen the mechanics for displaying the validation messages in previous articles. We can either add a call to Html.ValidationMessageFor for the properties that you are interested or a call to Html.ValidationSummary for the model as a whole.
In general this works fine and is all you need, but sometimes you may want something a little more sophisticated:
Here the author steps you through a few quick steps to add a container around the validation summary. This can be nice to give you more options in styling the look and feel of the validation summary.
Performing Validation in the Model Binder
Extending the Model Binder for Enhanced Validation [HowMVCWorks]
In this blog, Eric steps through a strategy for adding a custom validation method to your ViewModel and making the binder aware of this new method so that it gets incorporated into the validation process.
The advantage of this approach is that sometimes your validation logic is more complex than can easily be handled through attributes. The example Eric gives is when one property’s validation depends on the value of another property. This is actually a common scenario.
This may also come in handy if you want to incorporate authorization into the validations or validate input against data currently stored in the database such as setting range limits or max length values that may change after compile time.
Keith Bloom takes a different approach but ends up in a similar location – presenting an example of how to extend the validation process, and offering a warning of how NOT to extend the validation process.
Rather than striving for an architectural breakdown of the framework, Keith is chronicling his own initial investigations into the framework, complete with a brief overview of what ASP.NET MVC actually does (it’ll make sense when you read it) and, by extension, how the process of model binding actually works.
Keith covers a little more of the conceptual ground than Eric’s direct explanation of the inner workings, so this might be a useful piece if you’d like to get a slightly higher overview.
Specifying Validation Rules using Metadata
Using DataAnnotations for Validation [HowMVCWorks]
Once again we turn out attention to Eric’s excellent exploration of MVC. Here he gives a guided tour of the complexities of adding data validation attributes to a ViewModel. Turns out there really are no complexities for most cases. We simply add attributes to the properties in the ViewModel and let the binder handle the rest.
Creating New Data Annotation Validation Attributes [HowMVCWorks]
In a slightly different twist, Eric shows how you can create your own data validation attributes. This is also fairly straight forward and Eric provides a compelling reason for so.
While the RegularExpressionAttribute gives you the ultimate in flexibility it is also nearly the least ideal option for readability. Following Eric’s advice, why not derive attributes from RegularExpressionAttribute and encapsulate the actual regular expression.
Creating a Custom Validation Provider Enabling, Disabling, and Using Client-Side Validation
Creating a Custom ModelValidationProvider in ASP.NET MVC [The Code Project]
Vijaya Anand puts all the pieces together for creating a custom model validator. This is a rather advanced concept and one that you may never need because the default DataAnnotationModelValidatorProvider is pretty comprehensive.
In this case Vijaya needed to build his own so that the validation rules could come from an XML file instead of hard coded in attributes. If you need this level of flexibility, this article may give you some starters, but there are a few caveats to be aware of.
Vijaya points out some of these in the End section, you will want to cache the validation rules and not reparse the XML file everytime. His strategy also calls for a separate XML file for each ViewModel, you will want to make sure that this does not get out of hand and have run away memory consumption.
You will also want to make sure that the XML file can easily be validated and probably provide a tool for updating it ensure that it does not get corrupted.
The most insightful part of his code is his explanation of how the pieces fit together. Not only does this provide a good road map should you need to build your own custom validator, it also helps you understand the mechanics of building in substantial extensibility into your own libraries.
Customizing Client-Side Validation
Custom Client-Side Validation in ASP.NET MVC3 [The Code Project]
Rajendra steps the various steps needed to create extend custom validations on the client side. This is not needed if you limit yourself to the built in attributes, the .unobtrusive jquery validation scripts can easily handle these with no extra work.
If you add your own attributes and you want them validated client side, you need to do a few extra steps.
If you don’t follow these steps, the fields will still be validated; the user will just have to wait to get the validation messages. Depending on the type of validations and how you feel about pushing logic to the client, this may not be a big deal.
How To: Implement Remote Validation in ASP.NET MVC [MSDN Library]
Remote validation is an exciting feature introduced in MVC 3. It allows you to easily give validation messages on the client side without requiring a full post back but still keep the validation logic on the server. Essentially, you use attributes to specify an Action to be called to handle the validation and the framework will handle the heavy lifting of wiring up an AJAX method call to invoke the action.
You use the RemoteAttribute on the property that you want validated. With this attribute you specify the Controller and the Action. The action should return JsonResult specifying the error message if there is a problem or true if it passes validation.
The example showed in this article checks to see if a requested UserName is available. This is useful anytime you need real time validation and don’t want to require a full post back. This might be useful for checking an account balance, verifying inventory before processing an order, verifying time of day before accepting a request, etc.
This article also shows effective use of using Fiddler to help test and debug ajax calls. Fiddler is an invaluable tool that should be in every web developer’s bag of tricks.
Such validations were always available in the past; you just had to add the jquery code yourself. Now MVC 3 makes this incredibly easy.