How do you manually trigger the form validation in Blazor?
Nov 23, 2020
Blazor,
ASP .NET Core Blazor,
Blazor FAQ,
manually trigger form validation blazor,
5337 Views
This code will help you to understand how to manually trigger the form validation in Blazor.
You have to define and bind the EditContext with EditForm and then call the method editContext.Validate() on button click to manually trigger the validation.
@using System.ComponentModel.DataAnnotations;
<EditForm EditContext="@EC">
<DataAnnotationsValidator />
<ValidationSummary />
<div class="form-group d-flex justify-content-between">
<label class="col-form-label col-3" for="name">Time</label>
<InputText bind-Value="@model.Name" id="name" Class="form-control" />
</div>
<button type="button" onclick="@SubmitHandler" class="btn btn-primary">Submit</button>
</EditForm>
@code {
public class ModelClass
{
[Required]
public string Name { get; set; }
}
private ModelClass model { get; set; } = new ModelClass { Name = "" };
private EditContext EC { get; set; }
protected override void OnInitialized()
{
EC = new EditContext(model);
base.OnInitialized();
}
private void SubmitHandler()
{
EC.Validate(); // manually trigger the validation here
}
}