Ask Your Question

Revision history [back]

To validate a list object in MudBlazor, you can perform the following steps:

  1. Create a model that represents the list object and add data annotations to the list properties to specify validation rules.
public class Person
{
    [Required(ErrorMessage = "Name is required")] // Required validation rule for name property
    public string Name { get; set; }

    [Range(18, 60, ErrorMessage = "Age must be between 18 and 60")] // Range validation rule for age property
    public int Age { get; set; }
}
  1. Create a form for adding/editing the list object using MudBlazor's EditForm component.
<MudEditForm T="List<Person?>" EditContext="editContext" OnValidSubmit="@OnValidSubmit">
    <MudTable Items="@Model" Dense="true">
        <HeaderContent>
            <MudTh>T</MudTh>
            <MudTh>Name</MudTh>
            <MudTh>Age</MudTh>
        </HeaderContent>
        <RowTemplate>
            <MudTd>
                <MudTextField T="string" @bind-Value="@context.T"></MudTextField>
            </MudTd>
            <MudTd>
                <MudTextField T="string" @bind-Value="@context.Name"></MudTextField>
                <ValidationMessage For="@(()=> context.Name)"></ValidationMessage>
            </MudTd>
            <MudTd>
                <MudNumericField T="int" @bind-Value="@context.Age"></MudNumericField>
                <ValidationMessage For="@(()=> context.Age)"></ValidationMessage>
            </MudTd>
        </RowTemplate>
    </MudTable>
    <MudButton Color="Color.Primary" Variant="Variant.Filled" Type="submit">Submit</MudButton>
</MudEditForm>
  1. Define a validation callback method to handle the form submission and validation errors.
private async Task OnValidSubmit(EditContext editContext)
{
    try
    {
        if (ModelState.IsValid)
        {
            // list object is valid, proceed with submission
            // ...
        }
        else
        {
            // list object is invalid, display validation errors
            StateHasChanged();
        }
    }
    catch(Exception ex)
    {
        // handle any submission exceptions
    }
}

In the above implementation, the user is allowed to add multiple persons to the list object, and each person's name and age is validated against the specified data annotations. When the validation is successful, the OnValidSubmit method is invoked to handle the list object submission. Otherwise, the validation errors are displayed on the form.