ASP.NET MVC 1 had features built in that allowed you to validate content on the server-side, by specifying the elements to listen to validations for.  These features have been enhanced so that you can use a lambda to specify the field to validate.  Below is an illustration of these new features.

<% Html.BeginForm(); %>

<%= Html.ValidationSummary(“The following errors have happened:”) %>

 <legend>Form Values</legend>
  First: <%= Html.TextBoxFor(i => i.FirstName) %>
  <%= Html.ValidationMessageFor(i => i.FirstName, “*”) %>
  Last: <%= Html.TextBoxFor(i => i.LastName) %>
  <%= Html.ValidationMessageFor(i => i.LastName, “*”)%>
  Email: <%= Html.TextBoxFor(i => i.Email) %>
  <%= Html.ValidationMessageFor(i => i.Email, “*”)%>
 <input type=”submit” value=”Save” />

<% Html.EndForm(); %>

Here we use a lamdba to specify the field to validate; the field to display in a textbox and the field to validate are both specified via lambdas, which will use the property name as the field ID.  When the view posts back, the model binder validates the posted input, checking for validation errors.  The validation errors are stored in the ModelState object, which has an IsValid property.  When errors occur, IsValid is false, allowing you to control what happens next.  Any errors are displayed inline as a span with the error text that’s passed in (the second parameter).

Check out the post operation below to see how we process the input.

public ActionResult Index()
 return View(new ValidationTestClass { FirstName = “Bob”, LastName = “Anderson”, Email = “” });

public ActionResult Index(ValidationTestClass val)
  if (!ModelState.IsValid)
     return View();

    return RedirectToAction(“New”);

Now we have a check; when the post back to the server has errors, we redirect back to the view so the user can correct the errors within the view.  The MVC framework retains the form collection so the user can correct the issues; you do not need to do anything to do this.  When the user gets it right, the form posts back, and the redirection takes place.  In case you didn’t know, the model binder has the ability to parse the form values by their name and automatically assign them to the object that is the parameter, in this class, a class with properties.

So what is used to do the validation?  What you don’t see here is that a ModelMetadataProvider defines the rules for validating class instances.  By default, validation uses data annotations, and if you like, buddy classes, for validating classes.  So reflection extracts the attributes in the System.ComponentModel.DataAnnotations assembly, checks the data against these validation definitions, and then outputs the results in the UI.  Below is the class that represents the validations used for the above form.  Later on, we are going to look at the ModelMetadataProvider and how you can customize it, but for now, below is our test class:

public class ValidationTestClass
 [Required(ErrorMessage = “First name required.”)]
 public string FirstName { get; set; }

 [Required(ErrorMessage = “Last name required.”)]
 public string LastName { get; set; }

 Required(ErrorMessage = “Email  required.”),
 DataType(DataType.EmailAddress, ErrorMessage = “Invalid Email”)
 public string Email { get; set; }

Each property defines the type of rules that are validated, and the resulting error message if the validation fails.  Each validator can take property values to configure the type of validation, like the DataType attribute for the Email property.  The MVC framework takes these attribute definitions and validates these within the form.