"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Validation with the Data Annotation Validators (VB)

by Microsoft

Take advantage of the Data Annotation Model Binder to perform validation within an ASP.NET MVC application. Learn how to use the different types of validator attributes and work with them in the Microsoft Entity Framework.

In this tutorial, you learn how to use the Data Annotation validators to perform validation in an ASP.NET MVC application. The advantage of using the Data Annotation validators is that they enable you to perform validation simply by adding one or more attributes – such as the Required or StringLength attribute – to a class property.

Before you can use the Data Annotation validators, you must download the Data Annotations Model Binder. You can download the Data Annotations Model Binder Sample from the CodePlex website by clicking here.

It is important to understand that the Data Annotations Model Binder is not an official part of the Microsoft ASP.NET MVC framework. Although the Data Annotations Model Binder was created by the Microsoft ASP.NET MVC team, Microsoft does not offer official product support for the Data Annotations Model Binder described and used in this tutorial.

Using the Data Annotation Model Binder

In order to use the Data Annotations Model Binder in an ASP.NET MVC application, you first need to add a reference to the Microsoft.Web.Mvc.DataAnnotations.dll assembly and the System.ComponentModel.DataAnnotations.dll assembly. Select the menu option Project, Add Reference. Next click the Browse tab and browse to the location where you downloaded (and unzipped) the Data Annotations Model Binder sample (see Figure 1).

Figure 1: Adding a reference to the Data Annotations Model Binder (Click to view full-size image)

Select both the Microsoft.Web.Mvc.DataAnnotations.dll assembly and the System.ComponentModel.DataAnnotations.dll assembly and click the OK button.

You cannot use the System.ComponentModel.DataAnnotations.dll assembly included with .NET Framework Service Pack 1 with the Data Annotations Model Binder. You must use the version of the System.ComponentModel.DataAnnotations.dll assembly included with the Data Annotations Model Binder Sample download.

Finally, you need to register the DataAnnotations Model Binder in the Global.asax file. Add the following line of code to the Application_Start() event handler so that the Application_Start() method looks like this:

[!code-vbMain]

   1:  Protected Sub Application_Start()
   2:      RegisterRoutes(RouteTable.Routes)
   3:      ModelBinders.Binders.DefaultBinder = New Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder()
   4:  End Sub

This line of code registers the DataAnnotationsModelBinder as the default model binder for the entire ASP.NET MVC application.

Using the Data Annotation Validator Attributes

When you use the Data Annotations Model Binder, you use validator attributes to perform validation. The System.ComponentModel.DataAnnotations namespace includes the following validator attributes:

[!NOTE]

If your validation needs are not satisfied by any of the standard validators then you always have the option of creating a custom validator attribute by inheriting a new validator attribute from the base Validation attribute.

The Product class in Listing 1 illustrates how to use these validator attributes. The Name, Description, and UnitPrice properties are marked as required. The Name property must have a string length that is less than 10 characters. Finally, the UnitPrice property must match a regular expression pattern that represents a currency amount.

[!code-vbMain]

   1:  Imports System.ComponentModel
   2:  Imports System.ComponentModel.DataAnnotations
   3:   
   4:  Public Class Product
   5:   
   6:      Private _id As Integer
   7:      Private _name As String
   8:      Private _description As String
   9:      Private _unitPrice As Decimal
  10:   
  11:      Public Property Id() As Integer
  12:          Get
  13:              Return _id
  14:          End Get
  15:          Set(ByVal value As Integer)
  16:              _id = value
  17:          End Set
  18:      End Property
  19:   
  20:       _
  21:      Public Property Name() As String
  22:          Get
  23:              Return _name
  24:          End Get
  25:          Set(ByVal value As String)
  26:              _name = value
  27:          End Set
  28:      End Property
  29:   
  30:       _
  31:      Public Property Description() As String
  32:          Get
  33:              Return _description
  34:          End Get
  35:          Set(ByVal value As String)
  36:              _description = value
  37:          End Set
  38:      End Property
  39:   
  40:       _
  41:      Public Property UnitPrice() As Decimal
  42:          Get
  43:              Return _unitPrice
  44:          End Get
  45:          Set(ByVal value As Decimal)
  46:              _unitPrice = value
  47:          End Set
  48:      End Property
  49:   
  50:  End Class

Listing 1: Models.vb

The Product class illustrates how to use one additional attribute: the DisplayName attribute. The DisplayName attribute enables you to modify the name of the property when the property is displayed in an error message. Instead of displaying the error message “The UnitPrice field is required” you can display the error message “The Price field is required”.

[!NOTE]

If you want to completely customize the error message displayed by a validator then you can assign a custom error message to the validator’s ErrorMessage property like this: <Required(ErrorMessage:="This field needs a value!")>

You can use the Product class in Listing 1 with the Create() controller action in Listing 2. This controller action redisplays the Create view when model state contains any errors.

[!code-vbMain]

   1:  Public Class ProductController
   2:      Inherits System.Web.Mvc.Controller
   3:   
   4:      '
   5:      ' GET: /Product/Create
   6:   
   7:      Function Create() As ActionResult
   8:          Return View()
   9:      End Function
  10:   
  11:      '
  12:      ' POST: /Product/Create
  13:   
  14:       _
  15:      Function Create( ByVal productToCreate As Product) As ActionResult
  16:   
  17:          If Not ModelState.IsValid Then
  18:              Return View()
  19:          End If
  20:   
  21:          Return RedirectToAction("Index")
  22:   
  23:      End Function
  24:   
  25:  End Class

Listing 2: Controllers.vb

Finally, you can create the view in Listing 3 by right-clicking the Create() action and selecting the menu option Add View. Create a strongly-typed view with the Product class as the model class. Select Create from the view content dropdown list (see Figure 2).

Figure 2: Adding the Create View

[!code-aspxMain]

   1:  <%@ Page Title="" Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage(Of MvcApplication1.Product)" %>
   2:   
   3:  <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
   4:  Create
   5:  </asp:Content>
   6:   
   7:  <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
   8:   
   9:      <h2>Create</h2>
  10:   
  11:      <%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>
  12:   
  13:      <% Using Html.BeginForm()%>
  14:   
  15:          <fieldset>
  16:              <legend>Fields</legend>
  17:              <p>
  18:                  <label for="Name">Name:</label>
  19:                  <%= Html.TextBox("Name") %>
  20:                  <%= Html.ValidationMessage("Name", "*") %>
  21:              </p>
  22:              <p>
  23:                  <label for="Description">Description:</label>
  24:                  <%= Html.TextBox("Description") %>
  25:                  <%= Html.ValidationMessage("Description", "*") %>
  26:              </p>
  27:              <p>
  28:                  <label for="UnitPrice">UnitPrice:</label>
  29:                  <%= Html.TextBox("UnitPrice") %>
  30:                  <%= Html.ValidationMessage("UnitPrice", "*") %>
  31:              </p>
  32:              <p>
  33:                  <input type="submit" value="Create" />
  34:              </p>
  35:          </fieldset>
  36:   
  37:      <% End Using %>
  38:   
  39:      <div>
  40:          <%=Html.ActionLink("Back to List", "Index") %>
  41:      </div>
  42:   
  43:  </asp:Content>

Listing 3: Views.aspx

[!NOTE]

Remove the Id field from the Create form generated by the Add View menu option. Because the Id field corresponds to an Identity column, you don’t want to allow users to enter a value for this field.

If you submit the form for creating a Product and you do not enter values for the required fields, then the validation error messages in Figure 3 are displayed.

Figure 3: Missing required fields

If you enter an invalid currency amount, then the error message in Figure 4 is displayed.

Figure 4: Invalid currency amount

Using Data Annotation Validators with the Entity Framework

If you are using the Microsoft Entity Framework to generate your data model classes then you cannot apply the validator attributes directly to your classes. Because the Entity Framework Designer generates the model classes, any changes you make to the model classes will be overwritten the next time you make any changes in the Designer.

If you want to use the validators with the classes generated by the Entity Framework then you need to create meta data classes. You apply the validators to the meta data class instead of applying the validators to the actual class.

For example, imagine that you have created a Movie class using the Entity Framework (see Figure 5). Imagine, furthermore, that you want to make the Movie Title and Director properties required properties. In that case, you can create the partial class and meta data class in Listing 4.

Figure 5: Movie class generated by Entity Framework

[!code-vbMain]

   1:  Imports System.ComponentModel
   2:  Imports System.ComponentModel.DataAnnotations
   3:   
   4:   _
   5:  Partial Public Class Movie
   6:  End Class
   7:   
   8:  Public Class MovieMetaData
   9:   
  10:      Private _title As Object
  11:      Private _director As Object
  12:      Private _dateReleased As Object
  13:   
  14:       _
  15:      Public Property Title() As Object
  16:          Get
  17:              Return _title
  18:          End Get
  19:          Set(ByVal value As Object)
  20:              _title = value
  21:          End Set
  22:      End Property
  23:   
  24:       _
  25:      Public Property Director() As Object
  26:          Get
  27:              Return _director
  28:          End Get
  29:          Set(ByVal value As Object)
  30:              _director = value
  31:          End Set
  32:      End Property
  33:   
  34:       _
  35:      Public Property DateReleased() As Object
  36:          Get
  37:              Return _dateReleased
  38:          End Get
  39:          Set(ByVal value As Object)
  40:              _dateReleased = value
  41:          End Set
  42:      End Property
  43:  End Class

Listing 4: Models.vb

The file in Listing 4 contains two classes named Movie and MovieMetaData. The Movie class is a partial class. It corresponds to the partial class generated by the Entity Framework that is contained in the DataModel.Designer.vb file.

Currently, the .NET framework does not support partial properties. Therefore, there is no way to apply the validator attributes to the properties of the Movie class defined in the DataModel.Designer.vb file by applying the validator attributes to the properties of the Movie class defined in the file in Listing 4.

Notice that the Movie partial class is decorated with a MetadataType attribute that points at the MovieMetaData class. The MovieMetaData class contains proxy properties for the properties of the Movie class.

The validator attributes are applied to the properties of the MovieMetaData class. The Title, Director, and DateReleased properties are all marked as required properties. The Director property must be assigned a string that contains less than 5 characters. Finally, the DisplayName attribute is applied to the DateReleased property to display an error message like “The Date Released field is required.” instead of the error “The DateReleased field is required.”

[!NOTE]

Notice that the proxy properties in the MovieMetaData class do not need to represent the same types as the corresponding properties in the Movie class. For example, the Director property is a string property in the Movie class and an object property in the MovieMetaData class.

The page in Figure 6 illustrates the error messages returned when you enter invalid values for the Movie properties.

Figure 6: Using validators with the Entity Framework (Click to view full-size image)

Summary

In this tutorial, you learned how to take advantage of the Data Annotation Model Binder to perform validation within an ASP.NET MVC application. You learned how to use the different types of validator attributes such as the Required and StringLength attributes. You also learned how to use these attributes when working with the Microsoft Entity Framework.

Previous



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/mvc/overview/older-versions-1/models-data/validation-with-the-data-annotation-validators-vb.htm
< THANKS ME>