Computer Magic Logo
Validation Message

Wednesday, March 22, 2017

Published by Aristotelis Pitaridis

Let’s see how to display validation messages. We have the following model which will be used by our example.

using System.ComponentModel.DataAnnotations;

public class Student
{
    [Required]
    public string FirstName { get; set; }

    [MaxLength(2000)]
    public string Notes { get; set; }
}

In our controller we will need two actions. The first action will be used for the HTTP GET method and the second will be used for the HTTP POST method.

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public IActionResult Index(Student model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        return View();
    }
}

Now at the top of the view we define the model which will be used by our view.

@model Student

Finally, we have the form tag helper which contains our tag helper with the equivalent validation messages.

<form asp-controller="Home" asp-action="Index">
    <input asp-for="FirstName" />
    <span asp-validation-for="FirstName"></span>

    <textarea asp-for="Notes"></textarea>
    <span asp-validation-for="Notes"></span>

    <input class="btn btn-success" type="submit" />
</form>

This code will generate the following HTML.

<form action="/" method="post">
    <input type="text" data-val="true" data-val-required="The FirstName field is required." id="FirstName" name="FirstName" value="" />
    <span class="field-validation-valid" data-valmsg-for="FirstName" data-valmsg-replace="true"></span>

    <textarea data-val="true" data-val-maxlength="The field Notes must be a string or array type with a maximum length of &#x27;2000&#x27;." data-val-maxlength-max="2000" id="Notes" name="Notes"></textarea>
    <span class="field-validation-valid" data-valmsg-for="Notes" data-valmsg-replace="true"></span>

    <input class="btn btn-success" type="submit" />
    <input name="__RequestVerificationToken" type="hidden" value="CfDJ8Cc6bJ3TWmVAoCQJZSt8GLvBJkxe0ARxlfuScSIp3p-nBVOU1xwg1Ou4Et17JAeSqjOsiQVjTrRr_T3qgOlt3rw_EBm3UGacSYi6mLPKURPRkonW1ZapEJDUh05DJzEDImVXbxnRUfDc7SwyBLz0mA0" />
</form>