I am trying to implement the ObjectGraphDataAnnotationsValidator with a list of child components in Blazor. A list of Animals is bound in a form, rendered by a for loop. One of the properties of the Child class is Required.
This is the code:
Test.razor
@using System.ComponentModel.DataAnnotations
@page "/Test"
@code {
public class MyClass
{
public MyClass()
{
Animals = new List<AnimalItem>();
}
[Required]
public string FormName { get; set; }
public IList<AnimalItem> Animals { get; set; }
}
public class AnimalItem
{
[Required]
public string Name { get; set; }
}
protected override async Task OnInitializedAsync()
{
MyFormData = new MyClass()
{
Animals = new List<AnimalItem>()
{
new AnimalItem { Name = "Fuffy" },
new AnimalItem { Name = "Flaffy" }
}
};
await base.OnInitializedAsync();
}
public MyClass MyFormData { get; set; }
private void OnValidSubmit()
{
}
}
<EditForm Model="MyFormData" OnValidSubmit="@OnValidSubmit" >
<ObjectGraphDataAnnotationsValidator />
<ValidationSummary />
<InputText type="text" @bind-Value="MyFormData.FormName"/>
@foreach (var animal in MyFormData.Animals)
{
<Animal AnimalItem="animal"></Animal>
}
<button type="submit">Post</button>
</EditForm>
This is my component:
Animal.razor
@code {
[Parameter]
public Test.AnimalItem AnimalItem { get; set; }
}
<label for="Animal">Animal</label>
<InputText id="Animal" type="text" @bind-Value="@AnimalItem.Name" />
When I edit the components list and clear up the Name field, the form correctly informs me that the Name property is required. However, this doesn't prevent me from saving it if I press the submit button. What am I doing wrong? Any advice on how to debug the validation in Blazor is welcome :)
Thanks
I think you may need to add [ValidateComplexType] to the Animals collection on MyClass
public class MyClass
{
public MyClass()
{
Animals = new List<AnimalItem>();
}
[Required]
public string FormName { get; set; }
[ValidateComplexType]
public IList<AnimalItem> Animals { get; set; }
}
MS Docs Section on Complex Types
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