We’ve built a nice, simple data-entry application.
One problem with it, though, is that we don’t currently have
any type of input validation in place to ensure that fields are filled out
correctly within our Create Dinner form. Let’s fix that.
Adding Validation using DataAnnotations
Validation rules in an ASP.NET MVC based application are
usually best expressed within a model. This enables them to be maintained
in a single place, and enforced across any number of controllers and views that
might interact with them. ASP.NET MVC enables you to implement validation
rules using a variety of different mechanisms, and is flexible enough to
support just about any validation scheme you want to use.
ASP.NET MVC 2 includes built-in support for using .NET’s
System.ComponentModel.DataAnnotations library of validation rules – which
enable you to declaratively apply validation rules to model classes using
validation attributes. You can learn more about this capability in a previous blog post I wrote. We’ll take advantage of
this approach to enable input validation for our NerdDinner application.
Let’s go back to the Dinner class we defined earlier and add
some validation attributes to its properties (note: we need to add a “using
System.ComponentModel.DataAnnotations” namespace as well):
The [Required] validation attribute indicates that a
particular property must be specified. The [StringLength] validation
attribute allows us to indicate a maximum length for a particular string
property. The [RegularExpression] validation attribute allows us to
indicate that a particular string property must match a specified regular
expression in order to be valid – in this case an email address.
Each of the validation attributes supports an “ErrorMessage”
property – which allows us to specify an error message that should be displayed
if the validation fails. This can either be hard-coded as a string (like
above) or pulled from a resource – enabling it to be easily localized.