ValidationExtensions Class

Provides support for validating the input from an HTML form.

Namespace:  System.Web.Mvc.Html
Assembly:  System.Web.Mvc (in System.Web.Mvc.dll)

public static class ValidationExtensions

The ValidationExtensions class contains methods that extend the HtmlHelper class. The ValidationMessage method renders a validation message if the specified field contains incorrect input. The ValidationMessage method displays a list of all validation messages on the page. These methods require the view to be strongly typed.

If the DefaultModelBinder instance cannot bind a form-field value to the model, it adds an error to the ModelState object. When the form is rendered, the validation messages and validation summary are displayed based on the Errors property of the ModelState object.

You can control the appearance of the validation messages and validation summary by modifying the following cascading style sheet (CSS) classes in the Site.css file:

  • input-validation-error. This rule is applied to the input element that is rendered by the TextBox helper method.

  • field-validation-error. This rule is applied to the span element that is rendered by the ValidationMessage method.

  • validation-summary-error. This rule is applies to the ul element that is rendered by the ValidationMessage method.

The following example shows one way to use the ValidationSummary and ValidationMessage methods in MVC applications. This example defines a model class named Person. The Person class establishes the basic member requires. For example, Name must be a string and Age must be an integer.

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
}


The Create view enables the user to create a new Person object. A call to the ValidationSummary method is placed just before the entry form. If an invalid value is submitted, the summary displays the specified error message. Each form field makes a call to the ValidationMessage method directly after it. If the associated form field contains an invalid value, it will be marked with an asterisk (*).

<h2>Create</h2>

<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>

<% using (Html.BeginForm()) {%>

    <fieldset>
        <legend>Fields</legend>
        <p>
            <label for="Name">Name:</label>
            <%= Html.TextBox("Name") %>
            <%= Html.ValidationMessage("Name", "*") %>
        </p>
        <p>
            <label for="Age">Age:</label>
            <%= Html.TextBox("Age") %>
            <%= Html.ValidationMessage("Age", "*") %>
        </p>
        <p>
            <label for="Phone">Phone:</label>
            <%= Html.TextBox("Phone") %>
            <%= Html.ValidationMessage("Phone", "*") %>
        </p>
        <p>
            <label for="Email">Email:</label>
            <%= Html.TextBox("Email") %>
            <%= Html.ValidationMessage("Email", "*") %>
        </p>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>

<% } %>

<div>
    <%=Html.ActionLink("Back to List", "Index") %>
</div>


When the form is submitted, the Create action method handles the request. In this example, the Create method checks validation errors, such as whether the phone number and email address match the regular expressions that define a valid entry. If an error is found, an error message is added to the ModelState object and the Create view is re-displayed showing the errors.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Person person)
{
    if (person.Name.Trim().Length == 0)
    {
        ModelState.AddModelError("Name", "Name is required.");
    }
    if (person.Age < 1 || person.Age > 200)
    {
        ModelState.AddModelError("Age", "Age must be within range 1 to 200.");
    }
    if (!Regex.IsMatch(person.Phone, @"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}"))
    {
        ModelState.AddModelError("Phone", "Phone number is invalid.");
    }
    if (!Regex.IsMatch(person.Email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"))
    {
        ModelState.AddModelError("Email", "Email format is invalid.");
    }
    if (!ModelState.IsValid)
    {
        return View("Create", person);
    }

    people.Add(person);

    return RedirectToAction("List");
}


System.Object
  System.Web.Mvc.Html.ValidationExtensions

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Community Additions

Show: