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

Adding Validation to the Model (VB)

by Rick Anderson

This tutorial will teach you the basics of building an ASP.NET MVC Web application using Microsoft Visual Web Developer 2010 Express Service Pack 1, which is a free version of Microsoft Visual Studio. Before you start, make sure you’ve installed the prerequisites listed below. You can install all of them by clicking the following link: Web Platform Installer. Alternatively, you can individually install the prerequisites using the following links:

If you’re using Visual Studio 2010 instead of Visual Web Developer 2010, install the prerequisites by clicking the following link: Visual Studio 2010 prerequisites.

A Visual Web Developer project with VB.NET source code is available to accompany this topic. Download the VB.NET version. If you prefer C#, switch to the C# version of this tutorial.

In this section you’ll add validation logic to the Movie model, and you’ll ensure that the validation rules are enforced any time a user attempts to create or edit a movie using the application.

Keeping Things DRY

One of the core design tenets of ASP.NET MVC is DRY (“Don’t Repeat Yourself”). ASP.NET MVC encourages you to specify functionality or behavior only once, and then have it be reflected everywhere in an application. This reduces the amount of code you need to write and makes the code you do write much easier to maintain.

The validation support provided by ASP.NET MVC and Entity Framework Code First is a great example of the DRY principle in action. You can declaratively specify validation rules in one place (in the model class) and then those rules are enforced everywhere in the application.

Let’s look at how you can take advantage of this validation support in the movie application.

Adding Validation Rules to the Movie Model

You’ll begin by adding some validation logic to the Movie class.

Open the Movie.vb file. Add a Imports statement at the top of the file that references the System.ComponentModel.DataAnnotations namespace:

[!code-vbMain]

   1:  Imports System.ComponentModel.DataAnnotations

The namespace is part of the .NET Framework. It provides a built-in set of validation attributes that you can apply declaratively to any class or property.

Now update the Movie class to take advantage of the built-in Required, StringLength, and Range validation attributes. Use the following code as an example of where to apply the attributes.

[!code-vbMain]

   1:  Public Class Movie
   2:      Public Property ID() As Integer
   3:   
   4:      <Required(ErrorMessage:="Title is required")>
   5:      Public Property Title() As String
   6:   
   7:      <Required(ErrorMessage:="Date is required")>
   8:      Public Property ReleaseDate() As Date
   9:   
  10:      <Required(ErrorMessage:="Genre must be specified")>
  11:      Public Property Genre() As String
  12:   
  13:      <Required(ErrorMessage:="Price Required"), Range(1, 100, ErrorMessage:="Price must be between $1 and $100")>
  14:      Public Property Price() As Decimal
  15:   
  16:      <StringLength(5)>
  17:      Public Property Rating() As String
  18:  End Class

The validation attributes specify behavior that you want to enforce on the model properties they are applied to. The Required attribute indicates that a property must have a value; in this sample, a movie has to have values for the Title, ReleaseDate, Genre, and Price properties in order to be valid. The Range attribute constrains a value to within a specified range. The StringLength attribute lets you set the maximum length of a string property, and optionally its minimum length.

Code First ensures that the validation rules you specify on a model class are enforced before the application saves changes in the database. For example, the code below will throw an exception when the SaveChanges method is called, because several required Movie property values are missing and the price is zero (which is out of the valid range).

[!code-vbMain]

   1:  Dim db As New MovieDBContext()
   2:   
   3:  Dim movie As New Movie()
   4:  movie.Title = "Gone with the Wind"
   5:  movie.Price = 0.0D
   6:   
   7:  db.Movies.Add(movie)
   8:  db.SaveChanges() ' <= Will throw validation exception

Having validation rules automatically enforced by the .NET Framework helps make your application more robust. It also ensures that you can’t forget to validate something and inadvertently let bad data into the database.

Here’s a complete code listing for the updated Movie.vb file:

[!code-vbMain]

   1:  Imports System.Data.Entity
   2:  Imports System.ComponentModel.DataAnnotations
   3:   
   4:  Public Class Movie
   5:      Public Property ID() As Integer
   6:   
   7:      <Required(ErrorMessage:="Title is required")>
   8:      Public Property Title() As String
   9:   
  10:      <Required(ErrorMessage:="Date is required")>
  11:      Public Property ReleaseDate() As Date
  12:   
  13:      <Required(ErrorMessage:="Genre must be specified")>
  14:      Public Property Genre() As String
  15:   
  16:      <Required(ErrorMessage:="Price Required"), Range(1, 100, ErrorMessage:="Price must be between $1 and $100")>
  17:      Public Property Price() As Decimal
  18:   
  19:      <StringLength(5)>
  20:      Public Property Rating() As String
  21:  End Class
  22:   
  23:  Public Class MovieDBContext
  24:      Inherits DbContext
  25:      Public Property Movies() As DbSet(Of Movie)
  26:  End Class

Validation Error UI in ASP.NET MVC

Re-run the application and navigate to the /Movies URL.

Click the Create Movie link to add a new movie. Fill out the form with some invalid values and then click the Create button.

8_validationErrors

Notice how the form has automatically used a background color to highlight the text boxes that contain invalid data and has emitted an appropriate validation error message next to each one. The error messages match the error strings you specified when you annotated the Movie class. The errors are enforced both client-side (using JavaScript) and server-side (in case a user has JavaScript disabled).

A real benefit is that you didn’t need to change a single line of code in the MoviesController class or in the Create.vbhtml view in order to enable this validation UI. The controller and views you created earlier in this tutorial automatically picked up the validation rules that you specified using attributes on the Movie model class.

How Validation Occurs in the Create View and Create Action Method

You might wonder how the validation UI was generated without any updates to the code in the controller or views. The next listing shows what the Create methods in the MovieController class look like. They’re unchanged from how you created them earlier in this tutorial.

[!code-vbMain]

   1:  '
   2:  ' GET: /Movies/Create
   3:   
   4:  Function Create() As ViewResult
   5:      Return View()
   6:  End Function
   7:   
   8:  '
   9:  ' POST: /Movies/Create
  10:   
  11:  <HttpPost()>
  12:  Function Create(movie As Movie) As ActionResult
  13:      If ModelState.IsValid Then
  14:          db.Movies.Add(movie)
  15:          db.SaveChanges()
  16:          Return RedirectToAction("Index")
  17:      End If
  18:   
  19:      Return View(movie)
  20:  End Function

The first action method displays the initial Create form. The second handles the form post. The second Create method calls ModelState.IsValid to check whether the movie has any validation errors. Calling this method evaluates any validation attributes that have been applied to the object. If the object has validation errors, the Create method redisplays the form. If there are no errors, the method saves the new movie in the database.

Below is the Create.vbhtml view template that you scaffolded earlier in the tutorial. It’s used by the action methods shown above both to display the initial form and to redisplay it in the event of an error.

[!code-vbhtmlMain]

   1:  @ModelType MvcMovie.Movie
   2:   
   3:  @Code
   4:      ViewData("Title") = "Create"
   5:  End Code
   6:   
   7:  <h2>Create</h2>
   8:   
   9:  <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
  10:  <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
  11:   
  12:  @Using Html.BeginForm()
  13:      @Html.ValidationSummary(True)
  14:      @<fieldset>
  15:          <legend>Movie</legend>
  16:   
  17:          <div class="editor-label">
  18:              @Html.LabelFor(Function(model) model.Title)
  19:          </div>
  20:          <div class="editor-field">
  21:              @Html.EditorFor(Function(model) model.Title)
  22:              @Html.ValidationMessageFor(Function(model) model.Title)
  23:          </div>
  24:   
  25:          <div class="editor-label">
  26:              @Html.LabelFor(Function(model) model.ReleaseDate)
  27:          </div>
  28:          <div class="editor-field">
  29:              @Html.EditorFor(Function(model) model.ReleaseDate)
  30:              @Html.ValidationMessageFor(Function(model) model.ReleaseDate)
  31:          </div>
  32:   
  33:          <div class="editor-label">
  34:              @Html.LabelFor(Function(model) model.Genre)
  35:          </div>
  36:          <div class="editor-field">
  37:              @Html.EditorFor(Function(model) model.Genre)
  38:              @Html.ValidationMessageFor(Function(model) model.Genre)
  39:          </div>
  40:   
  41:          <div class="editor-label">
  42:              @Html.LabelFor(Function(model) model.Price)
  43:          </div>
  44:          <div class="editor-field">
  45:              @Html.EditorFor(Function(model) model.Price)
  46:              @Html.ValidationMessageFor(Function(model) model.Price)
  47:          </div>
  48:   
  49:   <div class="editor-label">
  50:       @Html.LabelFor(Function(model) model.Rating)
  51:   </div>
  52:   <div class="editor-field">
  53:       @Html.EditorFor(Function(model) model.Rating)
  54:       @Html.ValidationMessageFor(Function(model) model.Rating)
  55:   </div>
  56:   
  57:          <p>
  58:              <input type="submit" value="Create" />
  59:          </p>
  60:      </fieldset>
  61:  End Using
  62:   
  63:  <div>
  64:      @Html.ActionLink("Back to List", "Index")
  65:  </div>

Notice how the code uses an Html.EditorFor helper to output the <input> element for each Movie property. Next to this helper is a call to the Html.ValidationMessageFor helper method. These two helper methods work with the model object that’s passed by the controller to the view (in this case, a Movie object). They automatically look for validation attributes specified on the model and display error messages as appropriate.

What’s really nice about this approach is that neither the controller nor the Create view template knows anything about the actual validation rules being enforced or about the specific error messages displayed. The validation rules and the error strings are specified only in the Movie class.

If you want to change the validation logic later, you can do so in exactly one place. You won’t have to worry about different parts of the application being inconsistent with how the rules are enforced — all validation logic will be defined in one place and used everywhere. This keeps the code very clean, and makes it easy to maintain and evolve. And it means that that you’ll be fully honoring the DRY principle.

Adding Formatting to the Movie Model

Open the Movie.vb file. The System.ComponentModel.DataAnnotations namespace provides formatting attributes in addition to the built-in set of validation attributes. You’ll apply the DisplayFormat attribute and a DataType enumeration value to the release date and to the price fields. The following code shows the ReleaseDate and Price properties with the appropriate DisplayFormat attribute.

[!code-vbMain]

   1:  <DataType(DataType.Date)>
   2:      Public Property ReleaseDate() As Date
   3:   
   4:       <DataType(DataType.Currency)>
   5:      Public Property Price() As Decimal

Alternatively, you could explicitly set a DataFormatString value. The following code shows the release date property with a date format string (namely, “d”). You’d use this to specify that you don’t want to time as part of the release date.

[!code-vbMain]

   1:  <DisplayFormat(DataFormatString:="{0:d}")>
   2:      Public Property ReleaseDate() As Date

The following code formats the Price property as currency.

[!code-vbMain]

   1:  <DisplayFormat(DataFormatString:="{0:c}")>
   2:      Public Property Price() As Decimal

The complete Movie class is shown below.

[!code-vbMain]

   1:  Public Class Movie
   2:      Public Property ID() As Integer
   3:   
   4:      <Required(ErrorMessage:="Title is required")>
   5:      Public Property Title() As String
   6:   
   7:      <Required(ErrorMessage:="Date is required")>
   8:      <DataType(DataType.Date)>
   9:      Public Property ReleaseDate() As Date
  10:   
  11:      <Required(ErrorMessage:="Genre must be specified")>
  12:      Public Property Genre() As String
  13:   
  14:      <Required(ErrorMessage:="Price Required"), Range(1, 100, ErrorMessage:="Price must be between $1 and $100")>
  15:      <DataType(DataType.Currency)>
  16:      Public Property Price() As Decimal
  17:   
  18:      <StringLength(5)>
  19:      Public Property Rating() As String
  20:  End Class

Run the application and browse to the Movies controller.

8_format_SM
8_format_SM

In the next part of the series, we’ll review the application and make some improvements to the automatically generated Details and Delete methods..

Previous Next



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/mvc/overview/older-versions/getting-started-with-aspnet-mvc3/vb/adding-validation-to-the-model.htm
< THANKS ME>