How do we make the ValidationMessageFor include the child objects when validating?
My classes look like this:
public class Person
{
public Person()
{
Name = "";
FavoriteGame = "";
}
[Required(ErrorMessage = "Person's name is required and must not be empty.")]
public string Name { get; set; }
public string FavoriteGame { get; set; }
}
public class Team
{
public Team()
{
Name = "";
Game = "";
Coach = new Person();
}
[Required(ErrorMessage = "Team name is required and must not be empty.")]
public string Name { get; set; }
public string Game { get; set; }
public Person Coach { get; set; }
}
And my Blazor EditForm looks like this:
<EditForm Model="@myTeam" OnValidSubmit="@HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<div class="row p-4">
<label>Team Name:</label>
<InputText id="name" @bind-Value="@myTeam.Name" />
<ValidationMessage For="@(() => myTeam.Name)" />
</div>
<div class="row p-4">
<label>Team Game:</label>
<InputText id="name" @bind-Value="@myTeam.Game" />
<ValidationMessage For="@(() => myTeam.Game)" />
</div>
<div class="row p-4">
<label>Coach Name:</label>
<InputText id="name" @bind-Value="@myTeam.Coach.Name" />
<ValidationMessage For="@(() => myTeam.Coach.Name)" />
</div>
<div class="row p-4">
<label>Coach's Favorite Game:</label>
<InputText id="name" @bind-Value="@myTeam.Coach.FavoriteGame" />
<ValidationMessage For="@(() => myTeam.Coach.FavoriteGame)" />
</div>
<div class="row p-4">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</EditForm>
But during runtime, only the validation in class Team gets displayed...the validation of class Person gets skipped, and does not get invoked or displayed during runtime.
Is there a simple way of getting the ValidationMessageFor to work for class properties that are made of custom objects without getting into creating a whole new custom validator or a custom ValidationMessageFor component?
Please see the blazor documentation here: https://learn.microsoft.com/en-gb/aspnet/core/blazor/forms-validation?view=aspnetcore-3.1#nested-models-collection-types-and-complex-types
essentially you need to use the ObjectGraphDataAnnotationsValidator in the blazor form, and [ValidateComplexType] attribute
Learning from documentation pointed by @AppPack, these are the only changes needed to make this work:
Install Microsoft.AspNetCore.Components.DataAnnotations.Validation (prerelease) package
Use [ValidateComplexType] on the complex property (code sample below)
[ValidateComplexType] public Person Coach { get; set; }
Replace DataAnnotationsValidator with ObjectGraphDataAnnotationsValidator in the razor page
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With