Iteration #3 – Add form validation (C#)
by Microsoft
In the third iteration, we add basic form validation. We prevent people from submitting a form without completing required form fields. We also validate email addresses and phone numbers.
Building a Contact Management ASP.NET MVC Application (C#)
In this series of tutorials, we build an entire Contact Management application from start to finish. The Contact Manager application enables you to store contact information - names, phone numbers and email addresses - for a list of people.
We build the application over multiple iterations. With each iteration, we gradually improve the application. The goal of this multiple iteration approach is to enable you to understand the reason for each change.
Iteration #1 - Create the application. In the first iteration, we create the Contact Manager in the simplest way possible. We add support for basic database operations: Create, Read, Update, and Delete (CRUD).
Iteration #2 - Make the application look nice. In this iteration, we improve the appearance of the application by modifying the default ASP.NET MVC view master page and cascading style sheet.
Iteration #3 - Add form validation. In the third iteration, we add basic form validation. We prevent people from submitting a form without completing required form fields. We also validate email addresses and phone numbers.
Iteration #4 - Make the application loosely coupled. In this third iteration, we take advantage of several software design patterns to make it easier to maintain and modify the Contact Manager application. For example, we refactor our application to use the Repository pattern and the Dependency Injection pattern.
Iteration #5 - Create unit tests. In the fifth iteration, we make our application easier to maintain and modify by adding unit tests. We mock our data model classes and build unit tests for our controllers and validation logic.
Iteration #6 - Use test-driven development. In this sixth iteration, we add new functionality to our application by writing unit tests first and writing code against the unit tests. In this iteration, we add contact groups.
Iteration #7 - Add Ajax functionality. In the seventh iteration, we improve the responsiveness and performance of our application by adding support for Ajax.
This Iteration
In this second iteration of the Contact Manager application, we add basic form validation. We prevent people from submitting a contact without entering values for required form fields. We also validate phone numbers and email addresses (see Figure 1).
Figure 01: A form with validation (Click to view full-size image)
In this iteration, we add the validation logic directly to the controller actions. In general, this is not the recommended way to add validation to an ASP.NET MVC application. A better approach is to place an application s validation logic in a separate service layer. In the next iteration, we refactor the Contact Manager application to make the application more maintainable.
In this iteration, to keep things simple, we write all of the validation code by hand. Instead of writing the validation code ourselves, we could take advantage of a validation framework. For example, you can use the Microsoft Enterprise Library Validation Application Block (VAB) to implement the validation logic for your ASP.NET MVC application. To learn more about the Validation Application Block, see:
http://msdn.microsoft.com/en-us/library/dd203099.aspx
Adding Validation to the Create View
Let s start by adding validation logic to the Create view. Fortunately, because we generated the Create view with Visual Studio, the Create view already contains all of the necessary user interface logic to display validation messages. The Create view is contained in Listing 1.
Listing 1 - .aspx
[!code-aspxMain]
1: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ContactManager.Models.Contact>" %>
2:
3: <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
4: <title>Create</title>
5: </asp:Content>
6:
7: <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
8:
9: <%= Html.ValidationSummary() %>
10:
11: <% using (Html.BeginForm()) {%>
12:
13: <fieldset class="fields">
14: <legend>Create New Contact</legend>
15: <p>
16: <label for="FirstName">First Name:</label>
17: <%= Html.TextBox("FirstName") %>
18: <%= Html.ValidationMessage("FirstName", "*") %>
19: </p>
20: <p>
21: <label for="LastName">Last Name:</label>
22: <%= Html.TextBox("LastName") %>
23: <%= Html.ValidationMessage("LastName", "*") %>
24: </p>
25: <p>
26: <label for="Phone">Phone:</label>
27: <%= Html.TextBox("Phone") %>
28: <%= Html.ValidationMessage("Phone", "*") %>
29: </p>
30: <p>
31: <label for="Email">Email:</label>
32: <%= Html.TextBox("Email") %>
33: <%= Html.ValidationMessage("Email", "*") %>
34: </p>
35: <p class="submit">
36: <input type="submit" value="Create" />
37: </p>
38: </fieldset>
39:
40: <% } %>
41:
42: </asp:Content>
Notice the call to the Html.ValidationSummary() helper method that appears immediately above the HTML form. If there are validation error messages, then this method displays validation messages in a bulleted list.
Notice, furthermore, the calls to Html.ValidationMessage() that appear next to each form field. The ValidationMessage() helper displays an individual validation error message. In the case of Listing 1, an asterisk is displayed when there is a validation error.
Finally, the Html.TextBox() helper automatically renders a Cascading Style Sheet class when there is a validation error associated with the property displayed by the helper. The Html.TextBox() helper renders a class named input-validation-error.
When you create a new ASP.NET MVC application, a style sheet named Site.css is created in the Content folder automatically. This style sheet contains the following definitions for CSS classes related to the appearance of validation error messages:
[!code-cssMain]
1: .field-validation-error
2: {
3: color: #ff0000;
4: }
5:
6: .input-validation-error
7: {
8: border: 1px solid #ff0000;
9: background-color: #ffeeee;
10: }
11:
12: .validation-summary-errors
13: {
14: font-weight: bold;
15: color: #ff0000;
16: }
The field-validation-error class is used to style the output rendered by the Html.ValidationMessage() helper. The input-validation-error class is used to style the textbox (input) rendered by the Html.TextBox() helper. The validation-summary-errors class is used to style the unordered list rendered by the Html.ValidationSummary() helper.
[!NOTE]
You can modify the style sheet classes described in this section to customize the appearance of validation error messages.
Adding Validation Logic to the Create Action
Right now, the Create view never displays validation error messages because we have not written the logic to generate any messages. In order to display validation error messages, you need to add the error messages to ModelState.
[!NOTE]
The UpdateModel() method adds error messages to ModelState automatically when there is an error assigning the value of a form field to a property. For example, if you attempt to assign the string “apple” to a BirthDate property that accepts DateTime values, then the UpdateModel() method adds an error to ModelState.
The modified Create() method in Listing 2 contains a new section that validates the properties of the Contact class before the new contact is inserted into the database.
Listing 2 - Controllers.cs (Create with validation)
[!code-csharpMain]
1: //
2: // POST: /Contact/Create
3:
4: [AcceptVerbs(HttpVerbs.Post)]
5: public ActionResult Create([Bind(Exclude = "Id")] Contact contactToCreate)
6: {
7: // Validation logic
8: if (contactToCreate.FirstName.Trim().Length == 0)
9: ModelState.AddModelError("FirstName", "First name is required.");
10: if (contactToCreate.LastName.Trim().Length == 0)
11: ModelState.AddModelError("LastName", "Last name is required.");
12: if (contactToCreate.Phone.Length > 0 && !Regex.IsMatch(contactToCreate.Phone, @"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}"))
13: ModelState.AddModelError("Phone", "Invalid phone number.");
14: if (contactToCreate.Email.Length > 0 && !Regex.IsMatch(contactToCreate.Email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"))
15: ModelState.AddModelError("Email", "Invalid email address.");
16: if (!ModelState.IsValid)
17: return View();
18:
19: // Database logic
20: try
21: {
22: _entities.AddToContactSet(contactToCreate);
23: _entities.SaveChanges();
24: return RedirectToAction("Index");
25: }
26: catch
27: {
28: return View();
29: }
30: }
The validate section enforces four distinct validation rules:
- The FirstName property must have a length greater than zero (and it cannot consist solely of spaces)
- The LastName property must have a length greater than zero (and it cannot consist solely of spaces)
- If the Phone property has a value (has a length greater than 0) then the Phone property must match a regular expression.
- If the Email property has a value (has a length greater than 0) then the Email property must match a regular expression.
When there is a validation rule violation, an error message is added to ModelState with the help of the AddModelError() method. When you add a message to ModelState, you provide the name of a property and the text of a validation error message. This error message is displayed in the view by the Html.ValidationSummary() and Html.ValidationMessage() helper methods.
After the validation rules are executed, the IsValid property of ModelState is checked. The IsValid property returns false when any validation error messages have been added to ModelState. If validation fails, the Create form is redisplayed with the error messages.
[!NOTE]
I got the regular expressions for validating the phone number and email address from the regular expression repository at http://regexlib.com
Adding Validation Logic to the Edit Action
The Edit() action updates a Contact. The Edit() action needs to perform exactly the same validation as the Create() action. Instead of duplicating the same validation code, we should refactor the Contact controller so that both the Create() and Edit() actions call the same validation method.
The modified Contact controller class is contained in Listing 3. This class has a new ValidateContact() method that is called within both the Create() and Edit() actions.
Listing 3 - Controllers.cs
[!code-csharpMain]
1: using System.Linq;
2: using System.Text.RegularExpressions;
3: using System.Web.Mvc;
4: using ContactManager.Models;
5:
6: namespace ContactManager.Controllers
7: {
8: public class ContactController : Controller
9: {
10: private ContactManagerDBEntities _entities = new ContactManagerDBEntities();
11:
12: protected void ValidateContact(Contact contactToValidate)
13: {
14: if (contactToValidate.FirstName.Trim().Length == 0)
15: ModelState.AddModelError("FirstName", "First name is required.");
16: if (contactToValidate.LastName.Trim().Length == 0)
17: ModelState.AddModelError("LastName", "Last name is required.");
18: if (contactToValidate.Phone.Length > 0 && !Regex.IsMatch(contactToValidate.Phone, @"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}"))
19: ModelState.AddModelError("Phone", "Invalid phone number.");
20: if (contactToValidate.Email.Length > 0 && !Regex.IsMatch(contactToValidate.Email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"))
21: ModelState.AddModelError("Email", "Invalid email address.");
22: }
23:
24: public ActionResult Index()
25: {
26: return View(_entities.ContactSet.ToList());
27: }
28:
29: public ActionResult Create()
30: {
31: return View();
32: }
33:
34: [AcceptVerbs(HttpVerbs.Post)]
35: public ActionResult Create([Bind(Exclude = "Id")] Contact contactToCreate)
36: {
37: // Validation logic
38: ValidateContact(contactToCreate);
39: if (!ModelState.IsValid)
40: return View();
41:
42: // Database logic
43: try
44: {
45: _entities.AddToContactSet(contactToCreate);
46: _entities.SaveChanges();
47: return RedirectToAction("Index");
48: }
49: catch
50: {
51: return View();
52: }
53: }
54:
55: public ActionResult Edit(int id)
56: {
57: var contactToEdit = (from c in _entities.ContactSet
58: where c.Id == id
59: select c).FirstOrDefault();
60:
61: return View(contactToEdit);
62: }
63:
64: [AcceptVerbs(HttpVerbs.Post)]
65: public ActionResult Edit(Contact contactToEdit)
66: {
67: ValidateContact(contactToEdit);
68: if (!ModelState.IsValid)
69: return View();
70:
71: try
72: {
73: var originalContact = (from c in _entities.ContactSet
74: where c.Id == contactToEdit.Id
75: select c).FirstOrDefault();
76: _entities.ApplyPropertyChanges(originalContact.EntityKey.EntitySetName, contactToEdit);
77: _entities.SaveChanges();
78: return RedirectToAction("Index");
79: }
80: catch
81: {
82: return View();
83: }
84: }
85:
86: public ActionResult Delete(int id)
87: {
88: var contactToDelete = (from c in _entities.ContactSet
89: where c.Id == id
90: select c).FirstOrDefault();
91:
92: return View(contactToDelete);
93: }
94:
95: [AcceptVerbs(HttpVerbs.Post)]
96: public ActionResult Delete(Contact contactToDelete)
97: {
98: try
99: {
100: var originalContact = (from c in _entities.ContactSet
101: where c.Id == contactToDelete.Id
102: select c).FirstOrDefault();
103:
104: _entities.DeleteObject(originalContact);
105: _entities.SaveChanges();
106: return RedirectToAction("Index");
107: }
108: catch
109: {
110: return View();
111: }
112: }
113:
114: }
115: }
Summary
In this iteration, we added basic form validation to our Contact Manager application. Our validation logic prevents users from submitting a new contact or editing an existing contact without supplying values for the FirstName and LastName properties. Furthermore, users must supply valid phone numbers and email addresses.
In this iteration, we added the validation logic to our Contact Manager application in the easiest way possible. However, mixing our validation logic into our controller logic will create problems for us in the long term. Our application will be more difficult to maintain and modify over time.
In the next iteration, we will refactor our validation logic and database access logic out of our controllers. We’ll take advantage of several software design principles to enable us to create a more loosely coupled, and more maintainable, application.
|