I have a blazor EditForm tied to a model.
The model for example is StudentModel which has other class instantiated like lets say Phone.
public class Student
{
[Required]
public string Name {get; set;}
public Phone Phone {get; set;}
}
public class Phone
{
[Required]
public string Number {get; set;}
}
When validation runs on the form, the Name in the model does get validated, but the Number property on the Phone class does not. Why? How do I get properties validated that are in other classes but are instantiated in the model?
You have not shown how you have set up your form, but I imagine it is something like this:
If you want to validated nested complex properties, instead of using
<DataAnnotationsValidator />you can use
<ObjectGraphDataAnnotationsValidator />This validator can be used by installing the prerelease version of the
Microsoft.AspNetCore.Components.DataAnnotations.ValidationNuGet package.From the docs.
Edit
Thanks to MrC aka Shaun Curtis for making it clear in the comments that the package I have referenced was last updated in 2020 and should probably not be used for new projects that you want to maintain over future releases of .NET.
One thing to bear in mind is that if the approach you want to take doesn't seem to be well-supported, it might be worth re-thinking your approach.