I created an EditForm wrapping a table like so:
**Index.razor**
@using System.ComponentModel.DataAnnotations;
<EditForm @ref="Form" Model="vms" OnSubmit="Submit">
<DataAnnotationsValidator></DataAnnotationsValidator>
<table class="table">
<thead>
<tr>
<th>Code</th>
</tr>
</thead>
<tbody>
@foreach (var vm in vms)
{
<tr>
<td>
<InputText @bind-Value="vm.Code"></InputText>
<ValidationMessage For="@(() => vm.Code)"></ValidationMessage>
</td>
</tr>
}
</tbody>
</table>
<input type="submit" class="btn btn-primary" value="Submit" />
</EditForm>
@code{
List<MyClass> vms;
EditForm Form;
class MyClass
{
[Required(ErrorMessage ="Required")]
public string Code { get; set; }
}
protected override void OnInitialized()
{
vms = new List<MyClass>()
{
new MyClass()
{
Code = "1111"
},
new MyClass()
{
Code = "2222"
}
};
}
private void Submit()
{
bool IsValid = Form.EditContext.Validate();
}
}
The message error pops correctly as per the below image:
However, when I submit the form and then validate, it does not seem to pick up the invalid state.
It is still returning true after calling EditContext.Validate(), even though there are errors.
How do I get this to work? (How do I get false when at least one of the model item in the EditForm context is invalid so I can do my other validation stuff?)
[Updated 2021-01-16] Answers can also be found here. https://www.pragimtech.com/blog/blazor/validating-complex-models-in-blazor/
In short, the built-in DataAnnotationValidation does not work with arrays. To get it working, you must
- installMicrosoft.AspNetCore.Components.DataAnnotations.Validation
- Make the array an attribute and then decorate it with [ValidateComplexType]
- Use ObjectGraphDataAnnotationsValidator

