The purpose of this tutorial is to explain how you can perform validations within an ASP.NET MVC application. For example, you will learn how to prevent someone from submitting a form when the form does not have a value for a required field. You will learn how to use simple validations in mvc (the State Model and HTML Helper validation methods).

So, how to use simple Validations in ASP.NET MVC?

Understand the state model

You use the state model – or, more precisely, the state model dictionary – to represent validation errors. For example, the ActionResult Create () validates the properties of a product class ( Product ) before adding the product to a database.
Following is the ProductController.
// POST: /Product/Create

public ActionResult Create([Bind(Exclude="Id")] Product productToCreate)
    // Logique de validation
    if (productToCreate.Name.Trim().Length == 0)
        ModelState.AddModelError("Name", "Name is required.");
    if (productToCreate.Description.Trim().Length == 0)
        ModelState.AddModelError("Description", "Description is required.");
    if (productToCreate.UnitsInStock < 0)
        ModelState.AddModelError("UnitsInStock", "Units in stock cannot be less than zero.");
    if (!ModelState.IsValid)
        return View();

    // Logique de la base de données
        return RedirectToAction("Index");
        return View();

Name, description and unit stock of the Product class are validated. If any of these properties fail the validation test, an error message is added to the state model dictionary (represented by the ModelState property of the controller class).

If there are errors in the state model, then the ModelState.IsValid property returns false ( false ). In this case, the HTML form for creating a new product is redisplayed. Otherwise, if there are no validation errors, the new product is added to the database.

Validation Helpers methods

The ASP.NET MVC framework includes two validation Helper methods: the Html.ValidationMessage ()method and the Html.ValidationSummary ()method. You can use both methods in a view to view validation error messages.

The Html.ValidationMessage ()and Html.ValidationSummary ()methods are used in Create ()and Edit ()views that are automatically generated by the ASP.NET MVC framework.
Follow these steps to generate the Create view:

  • 1. Right-click the Create () action in the Product controller and select the Add View menu option.
  • 2. In the Add View dialog box, select the Create a strongly-typed view check box.
  • 3. In the View data class drop-down list , select the Product class.
  • 4. In the View Content drop-down list , select Create.
  • 5. Click the Add button.
Make sure you have compiled your application before adding a view. Otherwise, the class list will not appear in the View data class drop-down list.
How to Use Simple Validations in ASP.NET MVC? 1 300x211
How to Use Simple Validations in ASP.NET MVC? 2 278x300
After completing these steps, you get the Create view,

    <%= Html.ValidationSummary() %>

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

                <label for="Name">Name:</label>
                <%= Html.TextBox("Name") %>
                <%= Html.ValidationMessage("Name", "*") %>
                <label for="Description">Description:</label>
                <%= Html.TextBox("Description") %>
                <%= Html.ValidationMessage("Description", "*") %>
                <label for="Price">Price:</label>
                <%= Html.TextBox("Price") %>
                <%= Html.ValidationMessage("Price", "*") %>
                <label for="UnitsInStock">UnitsInStock:</label>
                <%= Html.TextBox("UnitsInStock") %>
                <%= Html.ValidationMessage("UnitsInStock", "*") %>
                <input type="submit" value="Create" />

    <% } %>

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

The Html.ValidationSummary ()method is called immediately above the HTML form. This method is used to display a list of validation error messages. The Html.ValidationSummary ()method displays errors in a bulleted list. The Html.ValidationMessage ()method is called next to each of the HTML form fields. This method is used to display an error message right next to a form field. In the case, the Html.ValidationMessage ()method displays an asterisk when there is an error.

Following shows how validations are rendered.

how to use simple validations in mvc  How to Use Simple Validations in ASP.NET MVC? 3 300x275

Note that the appearance of HTML input fields is also changed when there is a validation error. The Helper Html.TextBox () method generates a class = “input-validation-error” attribute when there is a validation error associated with the property rendered by the Html.TextBox ()method.

There are three cascading style sheet classes used to control the appearance of validation errors:

  • input-validation-error – applied to the <input> tag generated by the Html.TextBox () method.
  • field-validation-error – applied to the <span> tag generated by the Html.ValidationMessage () method.
  • validation-summary-errors – applied to the <ul> tag generated by the Html.ValidationSumamry () method
You can change the CSS of these classes, and thus change the appearance of validation errors, by modifying the Site.css file located in the Content folder.

Validation before Binding and validation after Binding

If you submit the HTML form for creating a product, and you enter an invalid value for the Price field and no value for the UnitsInStock field, then you will have the validation messages that can be seen in the following screenshot. Where do these validation error messages come from?
how to use validations in mvc  How to Use Simple Validations in ASP.NET MVC? 4 300x217
There are actually two types of validation error messages – those generated before the HTML form fields are linked to a class and those generated after the form fields are linked to the class. In other words, there are validation errors before binding (PreBinding) and validation errors after binding (PostBinding).The Create () action exposed by the Product controller accepts an instance of the Product class. The signature of the Create method looks like this,
public ActionResult Create([Bind(Exclude="Id")] Product productToCreate)

The values ​​of the HTML form fields are related to the productToCreate object by what is called a model binder . The default binding template adds an error message to the report template automatically when it can not link a form field to a form property.

The default binding template can not link the “apple” string to the Price property of the Product class. You can not assign a string to a decimal property. Therefore, the binding model adds an error to the state model.

The default binding template can not assign a null value to a property that does not accept it. In particular, the binding model can not assign a null value to the UnitsInStock property. Once again, the binding model drops its link attempt and adds an error message to the state template.

If you want to customize the appearance of these error messages before validation, you must create resource strings for these messages.