Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Model Validation should mention ModelState.AddModelError #27861

Closed
jfoshee opened this issue Dec 7, 2022 · 1 comment · Fixed by #28445
Closed

Model Validation should mention ModelState.AddModelError #27861

jfoshee opened this issue Dec 7, 2022 · 1 comment · Fixed by #28445
Assignees
Labels
code help wanted Sample code help wanted. doc-enhancement seQUESTered Identifies that an issue has been imported into Quest. Source - Docs.ms Docs Customer feedback via GitHub Issue

Comments

@jfoshee
Copy link
Contributor

jfoshee commented Dec 7, 2022

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

@dotnet-bot dotnet-bot added ⌚ Not Triaged Source - Docs.ms Docs Customer feedback via GitHub Issue labels Dec 7, 2022
@Rick-Anderson
Copy link
Contributor

Rick-Anderson commented Dec 8, 2022

@jfoshee you're right. It should also show how to add a model error to the model, not the property:

ModelState.AddModelError(string.Empty, "My error message");

Code goes with dotnet/AspNetCore.Docs.Samples#110

@Rick-Anderson Rick-Anderson self-assigned this Feb 15, 2023
@Rick-Anderson Rick-Anderson added the reQUEST Triggers an issue to be imported into Quest label Feb 15, 2023
@github-actions github-actions bot added seQUESTered Identifies that an issue has been imported into Quest. and removed reQUEST Triggers an issue to be imported into Quest labels Feb 15, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
code help wanted Sample code help wanted. doc-enhancement seQUESTered Identifies that an issue has been imported into Quest. Source - Docs.ms Docs Customer feedback via GitHub Issue
Projects
No open projects
Status: 🏗 In progress
Status: Done
Development

Successfully merging a pull request may close this issue.

3 participants