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 of the ASP.NET MVC framework are also focused on validating models. Because the framework is extensible, you can build validation schemes to work in any manner you require, but the default approach is a declarative style of validation using attributes known as data annotations.

In this chapter, you see how data annotations work with the MVC framework. You also see how annotations go beyond just validation. Annotations are a general-purpose mechanism you can use to feed metadata to the framework, and the framework drives not only validation from the metadata, but also uses the metadata when building the HTML to display and edit models. Let's start by looking at a validation scenario.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.38.92