Freigeben über


ValidationExtensions Class

Provides support for validating the input from an HTML form.

Inheritance Hierarchy

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

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

Syntax

'Declaration
<ExtensionAttribute> _
Public NotInheritable Class ValidationExtensions
public static class ValidationExtensions
[ExtensionAttribute]
public ref class ValidationExtensions abstract sealed

The ValidationExtensions type exposes the following members.

Properties

  Name Description
Public propertyStatic member ResourceClassKey Gets or sets the name of the resource file (class key) that contains localized string values.

Top

Methods

  Name Description
Public methodStatic member Validate Retrieves the validation metadata for the specified model and applies each rule to the data field.
Public methodStatic member ValidateFor<TModel, TProperty> Retrieves the validation metadata and validates each data field that is represented by the specified expression.
Public methodStatic member ValidationMessage(HtmlHelper, String) Displays a validation message if an error exists for the specified field in the ModelStateDictionary object.
Public methodStatic member ValidationMessage(HtmlHelper, String, IDictionary<String, Object>) Displays a validation message if an error exists for the specified field in the ModelStateDictionary object.
Public methodStatic member ValidationMessage(HtmlHelper, String, Object) Displays a validation message if an error exists for the specified field in the ModelStateDictionary object.
Public methodStatic member ValidationMessage(HtmlHelper, String, String) Displays a validation message if an error exists for the specified field in the ModelStateDictionary object.
Public methodStatic member ValidationMessage(HtmlHelper, String, String, IDictionary<String, Object>) Displays a validation message if an error exists for the specified field in the ModelStateDictionary object.
Public methodStatic member ValidationMessage(HtmlHelper, String, String, Object) Displays a validation message if an error exists for the specified field in the ModelStateDictionary object.
Public methodStatic member ValidationMessageFor<TModel, TProperty>(HtmlHelper<TModel>, Expression<Func<TModel, TProperty>>) Returns the HTML markup for a validation-error message for each data field that is represented by the specified expression.
Public methodStatic member ValidationMessageFor<TModel, TProperty>(HtmlHelper<TModel>, Expression<Func<TModel, TProperty>>, String) Returns the HTML markup for a validation-error message for each data field that is represented by the specified expression, using the specified message.
Public methodStatic member ValidationMessageFor<TModel, TProperty>(HtmlHelper<TModel>, Expression<Func<TModel, TProperty>>, String, IDictionary<String, Object>) Returns the HTML markup for a validation-error message for each data field that is represented by the specified expression, using the specified message and HTML attributes.
Public methodStatic member ValidationMessageFor<TModel, TProperty>(HtmlHelper<TModel>, Expression<Func<TModel, TProperty>>, String, Object) Returns the HTML markup for a validation-error message for each data field that is represented by the specified expression, using the specified message and HTML attributes.
Public methodStatic member ValidationSummary(HtmlHelper) Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object.
Public methodStatic member ValidationSummary(HtmlHelper, Boolean) Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object and optionally displays only model-level errors.
Public methodStatic member ValidationSummary(HtmlHelper, String) Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object.
Public methodStatic member ValidationSummary(HtmlHelper, Boolean, String) Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object and optionally displays only model-level errors.
Public methodStatic member ValidationSummary(HtmlHelper, String, IDictionary<String, Object>) Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object.
Public methodStatic member ValidationSummary(HtmlHelper, String, Object) Returns an unordered list (ul element) of validation messages in the ModelStateDictionary object.
Public methodStatic member ValidationSummary(HtmlHelper, Boolean, String, IDictionary<String, Object>) Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object and optionally displays only model-level errors.
Public methodStatic member ValidationSummary(HtmlHelper, Boolean, String, Object) Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object and optionally displays only model-level errors.

Top

Remarks

The ValidationExtensions class contains methods that extend the HtmlHelper class. The ValidationMessage method renders a validation message if the specified field contains invalid input. The ValidationSummary 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, the binder adds an error to the ModelState object. When the view 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.

Examples

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 requirements. For example, Name must be a string and Age must be an integer.

Public Class Person
    Private _Name As String
    Public Property Name() As String
        Get
            Return _Name
        End Get
        Set(ByVal value As String)
            _Name = value
        End Set
    End Property

    Private _Age As Integer
    Public Property Age() As Integer
        Get
            Return _Age
        End Get
        Set(ByVal value As Integer)
            _Age = value
        End Set
    End Property

    Private _Phone As String
    Public Property Phone() As String
        Get
            Return _Phone
        End Get
        Set(ByVal value As String)
            _Phone = value
        End Set
    End Property

    Private _Email As String
    Public Property Email() As String
        Get
            Return _Email
        End Get
        Set(ByVal value As String)
            _Email = value
        End Set
    End Property
End Class
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 in the view ahead of the entry form. If an invalid value is submitted, the summary displays an error message. A call is made to the ValidationMessage method following each form field. If the associated form field contains an invalid value, the field is 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>

<% End Using %>

<div>
    <%=Html.ActionLink("Back to List", "List")%>
</div>
<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)> _
Function Create(ByVal person As Person) As ActionResult
    If person.Name.Trim().Length = 0 Then
        ModelState.AddModelError("Name", "Name is required.")
    End If
    If ((person.Age < 1) Or (person.Age > 200)) Then
        ModelState.AddModelError("Age", "Age must be within range 1 to 200.")
    End If
    If Not (Regex.IsMatch(person.Phone, "((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}")) Then
        ModelState.AddModelError("Phone", "Phone number is invalid.")
    End If
    If Not (Regex.IsMatch(person.Email, "^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$")) Then
        ModelState.AddModelError("Email", "Email format is invalid.")
    End If
    If Not ModelState.IsValid Then
        Return View("Create", person)
    End If

    people.Add(person)

    Return RedirectToAction("List")
End Function
[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");
}

Thread Safety

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

See Also

Reference

System.Web.Mvc.Html Namespace