Skip to content

Model Validation should mention ModelState.AddModelError #27861

@jfoshee

Description

@jfoshee

aspnetcore/mvc/models/validation.md may be the first page someone reads about validation. Yet it seems to miss the simplest method to return a validation error to the user (where built-in attributes fall short): ModelState.AddModelError.

This method makes it particularly easy, for example, if the validation needs to check a database

if (dbContext.Records.Any(record => record.Name == model.Name))
{
    ModelState.AddModelError("Name", "The Name is already in use.");
    return View(model);
}

The existing documentation leads the reader to believe that creating a custom ValidationAttribute or implementing IValidatableObject are the only alternatives to built-in attributes.

Thanks for your consideration!


Document Details

Do not edit this section. It is required for learn.microsoft.com ➟ GitHub issue linking.


Associated WorkItem - 64069

Metadata

Metadata

Assignees

Labels

Source - Docs.msDocs Customer feedback via GitHub Issuecode help wantedSample code help wanted.doc-enhancementseQUESTeredIdentifies that an issue has been imported into Quest.

Type

No type
No fields configured for issues without a type.

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions