Skip to Main Content
ASP.NET 4 24-Hour Trainer
book

ASP.NET 4 24-Hour Trainer

by Toi B. Wright
July 2010
Beginner content levelBeginner
552 pages
10h 14m
English
Wrox
Content preview from ASP.NET 4 24-Hour Trainer

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; ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

ASP.NET 4 24-Hour Trainer

ASP.NET 4 24-Hour Trainer

Toi B. Wright
ASP.NET 4 Unleashed

ASP.NET 4 Unleashed

Stephen Walther, Kevin Hoffman, Nate Dudek

Publisher Resources

ISBN: 9780470596913Purchase bookExamplesErrata