Form validation is an important part of building reliable web applications. When users submit information through a registration form, checkout page, or profile update screen, the application needs to verify that the submitted data meets the required rules.
Blazor provides built-in validation components such as DataAnnotationsValidator, ValidationMessage, and ValidationSummary. These components make it easy to validate user input before submitting a form.
However, client-side validation is not enough for every scenario.
Consider a registration form where a user enters an email address. The value may have a valid email format, but the database might already contain an account with the same address. The browser cannot reliably determine this without communicating with the server.
The server must perform the actual validation and return an appropriate error response. Blazor then needs to display that error next to the corresponding form field.
In this article, we will explore how to handle server-side validation errors in Blazor forms, use EditContext and ValidationMessageStore, and build a reusable validation component that displays errors returned by an ASP.NET Core API.
Understanding Client-Side and Server-Side Validation
Before implementing the solution, it is important to understand the difference between client-side and server-side validation.
Client-side validation checks user input before sending a request to the server. It is useful for identifying common problems such as missing values, invalid email formats, and incorrect input lengths.
Server-side validation checks the submitted information using application rules, databases, and other trusted resources.
For example, consider a user registration form.
Validation rule | Validation location |
|---|---|
Name is required | Client and server |
Email format is valid | Client and server |
Email already exists | Server |
Phone number is already registered | Server |
User is eligible for registration | Server |
Required fields are missing | Client and server |
Client-side validation improves the user experience, but it should never be treated as the final authority.
A user can bypass browser validation or send an HTTP request without using the Blazor interface. Therefore, the server must validate every request independently.
Understanding EditContext and ValidationMessageStore
Blazor provides an EditContext object to manage the state of a form.
It tracks information such as:
The model associated with the form.
Modified fields.
Current validation messages.
Validation state changes.
When an EditForm uses a model, Blazor automatically creates an EditContext.
However, when server-side validation errors arrive from an API, Blazor needs a way to add those messages to the existing validation state.
This is where ValidationMessageStore becomes useful.
ValidationMessageStore allows developers to add and remove validation messages associated with specific fields.
For example, if the API returns an error stating that an email address is already registered, the application can associate that message with the Email property.
The ValidationMessage component can then display the error beside the corresponding input field.
Implementing Server-Side Validation Errors in Blazor
Let's create a practical registration form.
The application will use the following flow:
The user enters registration information.
Blazor performs client-side validation.
The form sends valid information to an ASP.NET Core API.
The API checks business rules and database constraints.
If validation fails, the API returns field-specific errors.
Blazor adds those errors to the form's validation state.
The user sees the messages beside the relevant fields.
Step 1. Create the Registration Model
First, create a model containing the registration information.
using System.ComponentModel.DataAnnotations;
public sealed class RegisterUserModel
{
[Required(ErrorMessage = "Name is required.")]
[StringLength(100)]
public string Name { get; set; } = string.Empty;
[Required(ErrorMessage = "Email is required.")]
[EmailAddress(ErrorMessage = "Enter a valid email address.")]
public string Email { get; set; } = string.Empty;
[Required(ErrorMessage = "Phone number is required.")]
public string PhoneNumber { get; set; } = string.Empty;
}Data annotation attributes define basic validation rules.
These rules can run in the Blazor form and can also be applied by the ASP.NET Core API when the server uses the same validation model.
Step 2. Create the ASP.NET Core API
Next, create an API endpoint that validates the submitted registration information.
For this example, assume that a user repository is available to check existing email addresses.
[ApiController]
[Route("api/users")]
public class UsersController : ControllerBase
{
private readonly IUserRepository _repository;
public UsersController(IUserRepository repository)
{
_repository = repository;
}
[HttpPost("register")]
public async Task<IActionResult> Register(
RegisterUserModel model,
CancellationToken cancellationToken)
{
bool emailExists = await _repository.EmailExistsAsync(
model.Email,
cancellationToken);
if (emailExists)
{
ModelState.AddModelError(
nameof(model.Email),
"This email address is already registered."
);
return ValidationProblem(ModelState);
}
bool phoneExists = await _repository.PhoneExistsAsync(
model.PhoneNumber,
cancellationToken);
if (phoneExists)
{
ModelState.AddModelError(
nameof(model.PhoneNumber),
"This phone number is already registered."
);
return ValidationProblem(ModelState);
}
return Ok(new
{
Message = "Registration completed successfully."
});
}
}The important part is ModelState.AddModelError.
It associates a validation message with a specific property.
The ValidationProblem method converts the ModelState errors into a standard HTTP 400 validation response.
The response contains an Errors object with field names and their corresponding error messages.
For example, the API might return:
{
"type": "https://tools.ietf.org/html/rfc9110",
"title": "One or more validation errors occurred.",
"status": 400,
"errors": {
"Email": [
"This email address is already registered."
]
}
}This structure allows the Blazor application to identify which field needs to display the error.
Step 3. Create a Reusable Custom Validation Component
Now create a component named CustomValidation.razor.
This component will receive server-side validation errors and add them to the current EditContext.
@implements IDisposable
@code {
[CascadingParameter]
private EditContext? CurrentEditContext { get; set; }
private ValidationMessageStore? messageStore;
protected override void OnInitialized()
{
if (CurrentEditContext is null)
{
throw new InvalidOperationException(
"CustomValidation requires an EditContext.");
}
messageStore = new ValidationMessageStore(
CurrentEditContext);
CurrentEditContext.OnFieldChanged += HandleFieldChanged;
}
public void DisplayErrors(
Dictionary<string, string[]> errors)
{
if (CurrentEditContext is null || messageStore is null)
return;
messageStore.Clear();
foreach (var error in errors)
{
var fieldIdentifier = new FieldIdentifier(
CurrentEditContext.Model,
error.Key);
messageStore.Add(
fieldIdentifier,
error.Value);
}
CurrentEditContext.NotifyValidationStateChanged();
}
public void ClearErrors()
{
messageStore?.Clear();
CurrentEditContext?.NotifyValidationStateChanged();
}
private void HandleFieldChanged(
object? sender,
FieldChangedEventArgs e)
{
messageStore?.Clear(e.FieldIdentifier);
CurrentEditContext?.NotifyValidationStateChanged();
}
public void Dispose()
{
if (CurrentEditContext is not null)
{
CurrentEditContext.OnFieldChanged -= HandleFieldChanged;
}
}
}There are a few important things happening here.
First, the component receives the current EditContext through a cascading parameter.
Next, it creates a ValidationMessageStore associated with that context.
The DisplayErrors method receives the API errors and converts each property name into a FieldIdentifier.
Finally, NotifyValidationStateChanged informs Blazor that the validation messages have changed.
The component also clears the server-side message for a field when the user modifies that field. This prevents an old server error from remaining visible after the user has corrected the input.
The Dispose method removes the event subscription when the component is removed.
Step 4. Create the Blazor Registration Form
Now create the registration page.
@page "/register"
@using System.Net.Http.Json
@using System.Text.Json.Serialization
@inject HttpClient Http
<EditForm Model="@Model" OnValidSubmit="HandleValidSubmit">
<DataAnnotationsValidator />
<CustomValidation @ref="customValidation" />
<ValidationSummary />
<div>
<label>Name</label>
<InputText @bind-Value="Model.Name" />
<ValidationMessage For="@(() => Model.Name)" />
</div>
<div>
<label>Email</label>
<InputText @bind-Value="Model.Email" />
<ValidationMessage For="@(() => Model.Email)" />
</div>
<div>
<label>Phone Number</label>
<InputText @bind-Value="Model.PhoneNumber" />
<ValidationMessage For="@(() => Model.PhoneNumber)" />
</div>
<button type="submit" disabled="@isSubmitting">
@(isSubmitting ? "Submitting..." : "Register")
</button>
</EditForm>
@if (!string.IsNullOrWhiteSpace(successMessage))
{
<p>@successMessage</p>
}
@if (!string.IsNullOrWhiteSpace(errorMessage))
{
<p>@errorMessage</p>
}
@code {
private RegisterUserModel Model = new();
private CustomValidation? customValidation;
private bool isSubmitting;
private string? successMessage;
private string? errorMessage;
private async Task HandleValidSubmit()
{
if (isSubmitting)
return;
isSubmitting = true;
successMessage = null;
errorMessage = null;
customValidation?.ClearErrors();
try
{
var response = await Http.PostAsJsonAsync(
"api/users/register",
Model);
if (response.StatusCode ==
System.Net.HttpStatusCode.BadRequest)
{
var result =
await response.Content
.ReadFromJsonAsync<ApiValidationProblem>();
if (result?.Errors is { Count: > 0 })
{
customValidation?.DisplayErrors(
result.Errors);
return;
}
}
response.EnsureSuccessStatusCode();
successMessage =
"Registration completed successfully.";
}
catch (HttpRequestException)
{
errorMessage =
"Unable to complete registration. Please try again.";
}
catch (OperationCanceledException)
{
errorMessage =
"The registration request was cancelled.";
}
finally
{
isSubmitting = false;
}
}
public sealed class ApiValidationProblem
{
[JsonPropertyName("errors")]
public Dictionary<string, string[]> Errors { get; set; }
= new();
}
}The form uses DataAnnotationsValidator for local validation and CustomValidation for errors returned by the API.
The important part is that the application does not display server-side errors using separate string properties for every field.
Instead, it adds them to the existing Blazor validation system.
This allows ValidationMessage and ValidationSummary to display both local and server-side errors.
Step 5. Understand the Result
Consider what happens when the user submits an email address that already exists.
The API returns a validation response containing an error associated with the Email property.
The Blazor component receives the response and calls DisplayErrors.
The ValidationMessage component associated with the email input automatically displays the message.
When the user changes the email address, the previous server-side error is cleared.
This provides a consistent experience without requiring developers to manually manage error messages for every input field.
The example assumes that the API returns property names matching the Blazor model. For nested objects or differently named properties, map the API field names to the appropriate Blazor model fields before creating FieldIdentifier instances.
Advantages and Disadvantages of Using ValidationMessageStore
Advantages
Reusable validation logic: A single custom validation component can handle errors from different API endpoints.
Consistent user experience: Local and server-side errors appear through the same validation components.
Field-specific messages: Errors can be displayed beside the relevant input rather than showing every problem in a generic message.
Better maintainability: Validation handling remains separate from individual form implementations.
Flexible error handling: Developers can add, remove, and update validation messages programmatically.
Disadvantages
Additional implementation: A custom validation component requires an EditContext and ValidationMessageStore.
Field mapping: API property names must match or be mapped to the corresponding Blazor model properties.
Network dependency: Server-side validation requires communication with the API.
Stale validation messages: Developers must clear old messages when fields change or a new submission begins.
More complex forms: Nested models and collections require additional handling when mapping server-side errors.
Best Practices for Handling Server-Side Validation Errors
Keep Server Validation Authoritative
Never depend entirely on Blazor validation.
Users can bypass client-side validation, so the API must independently validate every submitted request.
Return Structured Validation Responses
Use a consistent response format such as ValidationProblemDetails.
Avoid returning plain error strings when the application needs to identify which field caused the problem.
Clear Previous Errors Before Submitting
Always clear existing server-side messages before processing a new submission.
Otherwise, an old error can remain visible even after the server has accepted the corrected value.
Use Database Constraints for Data Integrity
Checking whether an email address already exists is useful, but it does not guarantee uniqueness.
Two users could submit the same email address at almost the same time.
Use a unique database constraint to protect the data and handle constraint violations appropriately.
Handle Network and Server Errors Separately
Not every unsuccessful API response is a validation failure.
A network timeout, authorization failure, or internal server error should not be displayed as an email validation message.
Handle these situations separately and provide a useful general error message.
Avoid Exposing Sensitive Server Information
Return validation messages that help users correct their input without revealing database details, internal exceptions, or implementation information.
Common Mistakes and Troubleshooting
Problem | Possible reason | Recommended solution |
|---|---|---|
Server errors are not displayed | ValidationMessageStore is not connected to the current EditContext | Use the cascading EditContext |
Errors appear only in the summary | The API field name does not match the model property | Correct the field mapping |
Old errors remain after editing | Messages are not cleared when fields change | Subscribe to OnFieldChanged |
Validation messages disappear unexpectedly | Another validation operation clears the same message store | Keep validation stores separate and manage their lifecycles |
API returns HTTP 400 without field errors | The response represents another kind of bad request | Inspect the response before treating it as validation |
Form submits multiple times | The submit button remains enabled during processing | Disable submission while the request is running |
Duplicate records are created | Validation and database insertion are separate operations | Enforce database constraints |
Summary
Displaying server-side validation errors is an important part of building reliable Blazor applications.
Built-in components such as DataAnnotationsValidator, ValidationMessage, and ValidationSummary handle local validation effectively. However, applications also need a consistent way to display errors returned by ASP.NET Core APIs.
EditContext and ValidationMessageStore provide that functionality. They allow developers to associate API validation errors with individual form fields and display them through the existing Blazor validation system.
A reusable custom validation component makes this process easier to maintain across multiple forms.
The most important practice is to keep server-side validation authoritative, return structured validation responses, clear outdated messages, and protect critical business rules with database constraints.
With this approach, Blazor applications can provide clear validation feedback while keeping form logic organized and maintainable.


Join the conversation! Your thoughts help the community grow.