Back To FAQ

Display error message using ValidationSymmary

ValidationSummary displays a list of validation error messages for all the fields. You can also display custom error messages using ValidationSummary, which is not related to any field.

Display Field Level Error Messages using ValidationSymmary

By default, ValidationSummary filters out field level error messages. If you want to display field level error messages as a summary then specify excludePropertyErrors = false.

Example: ValidationSummary to Display Errors
@Html.ValidationSummary(false, "", new { @class = "text-danger" })

So now, the following Edit view will display error messages as a summary at the top. Please make sure that you don't have ValidationMessageFor method for each fields.

Display error message using ValidationSymmary

Display Custom Error Messages

You can also display custom error message using ValidationSummary. For example, we want to display message if Student Name is already exists in the database.

To display custom error message, first of all, you need to add custom errors into ModelState in appropriate action method.

Example: Add Errors in ModelState
if (ModelState.IsValid) { 
              
    //check whether name is already exists in the database or not
    bool nameAlreadyExists = * check database *       
        
    if(nameAlreadyExists)
    {
        ModelState.AddModelError(string.Empty, "Student Name already exists.");
    
        return View(std);
    }
}

As you can see in the above code, we have added custom error messages using ModelState.AddModelError method. ValidationSummary method will automatically display all the error messages added into ModelState.

Error Messages in ValidationSymmary

Thus, you can use ValidationSummary helper method to display error messages.