Display custom validation error messages in ASP.NET MVC

Introduction


In order to display a custom validation error message in ASP.NET MVC, we use the ModelState method: AddModelError and the html helper: ValidationMessage.

AddModelError


The AddModelError method takes two params: a key that identifies the model error and a value that represents the error message to display. See the AddModelError method and its overloads for more information.

Example


public ActionResult Test(Student student)
{
    // if the student is not an adult yet
    if (student.age < 18) {
        ModelState.AddModelError("child", "You are not an adult !");

        return View("Index");
    }

    // if the student is an adult, do something else
    return RedirectToAction("Index", "Home");
}

In preceding code, we check if the student is an adult or not based on his age. If the student's age is less than 18 years old, we set our custom error message by using the AddModelError method which takes also a unique identifier.

In the HTML form, we pass the model error key as a parameter of the ValidationMessage method like this:

ValidationMessage

If the student is an adult, the user will get redirected to the Index action of the Home controller. Otherwise, he will get the following error message: You are not an adult !

See also