Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor validation of List of Child Components

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

like image 592
ab_732 Avatar asked Nov 23 '25 11:11

ab_732


1 Answers

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

like image 127
MrC aka Shaun Curtis Avatar answered Nov 27 '25 23:11

MrC aka Shaun Curtis