How do you share validation logic between a Blazor form (using EditForm and DataAnnotationsValidator) and a corresponding ASP.NET Core Web API's model validation?
Short answer
Since both Blazor's EditForm/DataAnnotationsValidator and ASP.NET Core's [ApiController] automatic model validation read the same System.ComponentModel.DataAnnotations attributes ([Required], [StringLength], [Range]) on a shared DTO/model class, defining validation rules once on…
Advertisement
AModel answer
Since both Blazor's EditForm/DataAnnotationsValidator and ASP.NET Core's [ApiController] automatic model validation read the same System.ComponentModel.DataAnnotations attributes ([Required], [StringLength], [Range]) on a shared DTO/model class, defining validation rules once on a model referenced by both the Blazor client project and the API project (via a shared class library) ensures consistent validation behavior on both the client (immediate UX feedback) and server (authoritative enforcement) without duplicating rules.
// Shared/ProductDto.cs (referenced by both Blazor client and API projects)
public class ProductDto {
[Required, StringLength(100)] public string Name { get; set; }
[Range(0.01, 10000)] public decimal Price { get; set; }
}
<!-- Blazor component -->
<EditForm Model="product" OnValidSubmit="Submit">
<DataAnnotationsValidator />
<ValidationSummary />
<InputText @bind-Value="product.Name" />
</EditForm>Real-world example
A shared ProductDto class in a common library is referenced by both the Blazor WebAssembly client (for instant client-side form validation feedback) and the ASP.NET Core API (for authoritative server-side validation), guaranteeing both layers enforce identical rules.
Likely follow-ups
- Why must server-side validation still be enforced even with client-side validation in place?
- How does this shared-model pattern work when Blazor Server and the API are the same project?
Related topics