Blazor comes with everything needed to create forms and validate them. You can create a form and validate fields using data annotations.

<EditForm Model="model">
    <DataAnnotationsValidator />

    <InputText @bind-Value="model.Text" />
    <ValidationMessage For="() => model.Text" />

    <div>
        Current value: @model.Text
    </div>

    <button class="btn btn-primary" type="submit">Submit</button>
</EditForm>

@code{
    Model model = new Model();

    class Model
    {
        [StringLength(maximumLength: 10, MinimumLength = 3)]
        public string Text { get; set; }
    }
}

While this works well, the validation occurs when the input loses the focus:

The <InputText> component uses the onchange event to bind the value, and so, to trigger the validation. This event is fired when the user commits the element’s value. For a text input this means when the element loses focus. When you use the @bind directive, you can set the event to use. However, the InputTextcomponent doesn’t expose another event. Let’s try with a raw <input> element, so we can use the oninput event to bind the value:

<EditForm Model="model">
    <DataAnnotationsValidator />

    <input type="text" @bind-value="model.Text" @bind-value:event="oninput" />
    <ValidationMessage For="() => model.Text" />

    <div>
        Current value: @model.Text
    </div>

    <button class="btn btn-primary" type="submit">Submit</button>
</EditForm>

This time, the value is bound after every keystroke. But, the validation doesn’t work anymore 😦

#blazor #.net #asp.net core #web

Validating an input on keypress instead of on change in Blazor
20.50 GEEK