Chapter 17B. Data Annotation Validators in MVC

In Lesson 16B you saw how to add custom validation code to the controller. However, it is a much better practice not to include validation logic in the controller. One way to add simple data validation to your application without adding code to the controller is to use Data Annotation validators. In this lesson I show you how to annotate your model using Data Annotation validators.

To use Data Annotation validators you must add the following using statement to the code on your page:

using System.ComponentModel.DataAnnotations;

These are the validation attributes that are included in the DataAnnotations namespace:

  • CustomValidation — This attribute is used to specify a custom validation method at run time.

  • Range — This attribute is used to define the valid range for the value.

  • RegularExpression — This attribute is used to provide the regular expression with which the value is compared.

  • Required — This attribute is used to indicate that a value is required.

  • StringLength — This attribute can be used to specify both the minimum and maximum number of characters for the value.

    Note

    The DataAnnotations namespace provides a large number of attribute classes. I am only demonstrating the validation attribute classes in this lesson.

This is the model I use for this lesson:

using System.ComponentModel.DataAnnotations; namespace Lesson17b.Models { public class Contact { [Required] public string Name { get; set; } [Required] [Range(0, 110)] public int Age { get; ...

Get ASP.NET 4 24-Hour Trainer 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.