I want to validate a Blazor form even though the user hasn't changed the value of any form fields. (By default, Blazor only validates fields after they are modified.)
How can I validate the form without requiring user interaction (editing a field, clicking a button, etc.)? I want to validate the form when it initially shows.
Here is my code:
@using System.ComponentModel.DataAnnotations
@page "/"
<EditForm Model="@formModel" Context="currentEditContext">
<DataAnnotationsValidator />
<p>
<label>My Text: <InputText @bind-Value="formModel.Text" /></label>
<ValidationMessage For="@(() => formModel.Text)" />
</p>
<p>Form valid: @currentEditContext.Validate()</p>
</EditForm>
@code
{
FormModel formModel = new();
private class FormModel
{
[Required]
public string Text { get; set; } = "";
}
}
I tried using various methods on my EditContext object, but none of them triggered validation.
editContext.Validate();editContext.NotifyValidationStateChanged();editContext.NotifyFieldChanged(editContext.Field("Text"));