Course contentsShow
← C#
Lesson 1332 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

Form Validation with Blazor

Validate user input in real-time using EditForm and custom validation components.

In this lesson, you will learn how to implement real-time, declarative form validation in Blazor using the EditForm component and Data Annotations.

The Mechanics of EditForm

In Blazor, EditForm is the backbone of user input. Unlike standard HTML forms, it integrates seamlessly with the Blazor rendering pipeline to track the state of your model. When you wrap your inputs in an EditForm and provide a Model, Blazor automatically hooks into data binding to perform validation whenever a user interacts with a field.

To handle the actual validation rules, we use Data Annotations (like [Required] or [StringLength]) directly on our model's properties.

Real-Time Validation

To trigger validation in real-time, we use an EditContext. This object tracks which fields have been modified and their current validation status. By default, EditForm validates when the user attempts to submit, but we can hook into the OnFieldChanged event to provide immediate feedback:

<EditForm EditContext="@editContext">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <InputText @bind-Value="user.Username" />
    <ValidationMessage For="@(() => user.Username)" />
    
    <button type="submit">Submit</button>
</EditForm>

@code {
    private User user = new();
    private EditContext? editContext;

    protected override void OnInitialized()
    {
        editContext = new(user);
        // Trigger validation whenever a field changes
        editContext.OnFieldChanged += (s, e) => editContext.Validate();
    }
}

Why This Matters

By subscribing to OnFieldChanged and calling editContext.Validate(), you shift the validation experience from a "submit-and-wait" model to an interactive one. The ValidationMessage component automatically listens to the EditContext and updates the DOM the moment a rule is broken—or fixed—without needing to manually manage error strings or toggle CSS classes yourself. This keeps your component code clean while providing high-quality UX.

Key Takeaway: By utilizing the EditContext and binding it to your model's Data Annotations, you can create a responsive, real-time validation loop that updates your UI automatically as users type.