C
C#2y ago
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>();
}
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>
<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>
2 Replies
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Binto86
Binto86OP2y ago
For anyone interested, i solved it by creating Component for Person and called it every time in the loop. I set the editcontext of the person form by hand. Than on submit i looped through every person and called context.Validate() and if any of the people returned false i didn't proced with the submiting.
Want results from more Discord servers?
Add your server