How do you 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
    }
}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.