In Blazor, execute a method after validating an InputText by DataAnnotation

302 Views Asked by At

I need to check if data typed in a inputtext is valid, and if it is, then execute a method. (Validation by a DataAnnotation).

I tried in the OnFieldChanged event of EditForm but this one executes before validation.

How could I do this?

1

There are 1 best solutions below

3
On

The parameter OnValidSubmit in EditForm can do this. Here is an example:

MyModel.cs

using System;
using System.ComponentModel.DataAnnotations;

public class MyModel
{
    [Required]
    public string Field1 { get; set; }
    [Required, Range(1, 10)]
    public int Fields2 { get; set; } = 1;
}

MyPage.razor

<EditForm Model="@exampleModel" OnValidSubmit="@HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <InputText id="field1" @bind-Value="@exampleModel.Field1"></InputText>
    <button type="submit">Submit</button>
</EditForm>

<h5 hidden="@(!isFormValid)">Form submitted successfully!</h5>

@code {
    MyModel exampleModel = new MyModel();
    bool isFormValid = false;

    void HandleValidSubmit()
    {
        isFormValid = true;
        StateHasChanged();
    }
}

Invalid submit:

enter image description here

Valid submit:

enter image description here