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"));
I discovered that I can trigger the form validation by running editContext.Validate()
inside OnAfterRender()
.
This code validates the form immediately upon loading the page:
@using System.ComponentModel.DataAnnotations
@page "/"
<EditForm EditContext="editContext">
<DataAnnotationsValidator />
<p>
<label>My Text: <InputText @bind-Value="formModel.Text" /></label>
<ValidationMessage For="@(() => formModel.Text)" />
</p>
<p>Form valid: @(!editContext.GetValidationMessages().Any())</p>
</EditForm>
@code
{
FormModel formModel = new();
EditContext editContext;
private class FormModel
{
[Required]
public string Text { get; set; } = "";
}
protected override void OnInitialized()
{
editContext = new(formModel);
base.OnInitialized();
}
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
editContext.Validate();
StateHasChanged(); // Update the "Form valid" message
}
base.OnAfterRender(firstRender);
}
}