Open lauraposner opened 4 months ago
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
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