C#C
C#3y ago
2 replies
Binto86

✅ Validate input in list in blazor forms

I have blazor EditForm with some inputs, the user can enter multiple people into the form, i handle that by having a button that adds some new fields in which the user can fill out new person. The
bind-value
for those inputs is the certain index list of people i have inside the main class for model (for example
modelClass.People[5]
). Now i want to add input validation for example for email, but it doesn't get validated for the inputs that write inside the list. Anyone any idea how to make it work?
this is the relevant part of my code:
public class Person
{
    [Required]
    public string FullName { get; set; }

    [Required]
    [EmailAddress]
    public string Email { get; set; }
}

public class Company
{
    [Required]
    public string Name{ get; set; }

    public List<Person> People = new List<Person>();
}


<EditForm class="form" Model="reg" OnValidSubmit="Submit"> 
    <DataAnnotationsValidator />
    <ValidationSummary />

    <label>Name of the company:</label> <InputText class="field" @bind-Value="reg.Firm"> <br />
    @for (int i = 0; i < people; i++)
    {
        <h4>@(i + 1). Person</h4>
        @AddPersonIfNeeded();
        <div class="form">
            <label>Fullname:</label> <InputText class="field" @bind-Value="reg.People[0].FullName" /> <br />
            <label>Email:</label> <InputText class="field" @bind-Value="reg.People[0].Email"/> <br />
        </div>
    }
    <button type="button" class="button" onclick="@(() => { people++; })">Add new person</button>
    <button type="submit" class="button">Submit</button>
</EditForm>
Was this page helpful?