Chapter 6

Data Annotations and Validation

— By K. Scott Allen

What's In This Chapter?

  • Using data annotations for validation
  • How to create your own validation logic
  • Using model metadata annotations

Validating user input has always been challenging for web developers. Not only do you want validation logic executing in the browser, but you also must have validation logic running on the server. The client validation logic gives users instant feedback on the information they enter into a form, and is an expected feature in today's web applications. Meanwhile, the server validation logic is in place because you should never trust information arriving from the network.

Once you look at the bigger picture, however, you realize how logic is only one piece of the validation story. You also need to manage the user-friendly (and often localized) error messages associated with validation logic, to place the error messages in your UI, and to provide some mechanism for users to recover gracefully from validation failures.

If validation sounds like a daunting chore, you'll be happy to know the MVC framework can help you with the job. This chapter is devoted to giving you everything you need to know about the validation components of the MVC framework.

When you talk about validation in an MVC design pattern context, you are primarily focusing on validating model values. Did the user provide a required value? Is the value in range? It should come as no surprise, when you find the validation features ...

Get Professional ASP.NET MVC 3 now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.