Custom Validation Logic
The extensibility of the ASP.NET MVC framework means an infinite number of possibilities exist for implementing custom validation logic. However, this section focuses on two core scenarios:
- Packaging validation logic into a custom data annotation
- Packaging validation logic into a model object itself
Putting validation logic into a custom data annotation means you can easily reuse the logic across multiple models. Of course, you have to write the code inside the attribute to work with different types of models, but when you do, you can place the new annotation anywhere.
On the other hand, adding validation logic directly to a model object often means the validation logic itself is easier to write (you only need to worry about the logic working with a single type of object). It is, however, more difficult to reuse the logic.
You'll see both approaches in the following sections, starting with writing a custom data annotation.
Custom Annotations
Imagine you want to restrict the last name value of a customer to a limited number of words. For example, you might say that 10 words are too many for a last name. You also might decide that this type of validation (limiting a string to a maximum number of words) is something you can reuse with other models in the Music Store application. If so, the validation logic is a candidate for packaging into a reusable attribute.
All of the validation annotations (like Required and Range) ultimately derive from the ValidationAttribute ...
Get Professional ASP.NET MVC 4 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.