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

Does ModelState.IsValid evaluated on a Movie object validate Genre against its own validation attributes? #32594

Open
lauraposner opened this issue May 17, 2024 · 1 comment
Assignees
Labels

Comments

@lauraposner
Copy link

lauraposner commented May 17, 2024

Description

What I was wondering is whether ModelState.IsValid evaluated on a Movie object would also validate its Genre property value against any validation attributes on the Genre class itself. From my testing it appears the answer is no. It would be helpful to note this in the documentation and perhaps to provide an example where if you want to validate the Genre property value against the Genre class validation attributes you could, for example, use TryValidateModel(movie.Genre, nameof(Genre)) instead.

Page URL

https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-8.0

Content source URL

https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/mvc/models/validation.md

Document ID

615db388-a244-41f7-21b5-a4085d9ed479

Article author

@Rick-Anderson

@Rick-Anderson
Copy link
Contributor

Rick-Anderson commented May 21, 2024

Thanks for pointing this out. I'll add this information to an include file so I can add it to Model validation in ASP.NET Core MVC and Razor Pages, this tutorial, and the other tutorials that use model validation.

When ModelState.IsValid method is called on a model object (e.g. Movie ), only properties on that model that are primitive types, strings , or numbers are validated. Validation doesn't automatically traverse into nested objects (like Genre) and collections with the validation attributes defined on their classes.

For example, to Genre in the Movie class, use TryValidateModel(movie.Genre, nameof(Genre))

Fix #32578

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: To do
Development

No branches or pull requests

3 participants