What you'll learn
This article shows how to validate Blazor WebAssembly forms with data annotations and DataAnnotationsValidator. It covers a simple client name field and a booking form with nested contact details, collection items, cross-property rules, and lookup-only data.
The examples target .NET 11. The booking form uses validation metadata generated at build time.
Why it matters
When nested validation isn't configured, a booking can pass top-level validation even if its item quantity is 0 or its contact email is blank. Without generated metadata, DataAnnotationsValidator falls back to top-level model validation on submit; missing metadata doesn't produce a runtime error.
Field messages help users correct input where they entered it, while a summary shows errors across the form. A partial catalogue record has a different purpose: treating it as a booking item could block an otherwise valid form. Client-side checks improve feedback, but your server must independently validate submitted data before processing it.
Implementation
Validate a client name with built-in attributes
Add Required and MaxLength to the name, then put DataAnnotationsValidator inside the EditForm. This self-contained example follows the simple demo; it needs no generated metadata for its top-level field.
@using System.ComponentModel.DataAnnotations
<EditForm Model="@exampleModel" OnValidSubmit="@HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<label for="name">Name</label>
<InputText id="name" @bind-Value="exampleModel.Name" />
<ValidationMessage For="@(() => exampleModel.Name)" />
<button type="submit">Submit</button>
<p>@message</p>
</EditForm>
@code {
public class ExampleModel
{
[Required(ErrorMessage = "Name is required.")]
[MaxLength(50, ErrorMessage = "Name too long (50 character limit).")]
public string? Name { get; set; }
}
private ExampleModel exampleModel = new();
private string? message;
private void HandleValidSubmit()
{
message = "HandleValidSubmit called";
}
}
ValidationMessage displays errors for the named field; ValidationSummary displays form-wide errors. Field validation runs when the field changes, and OnValidSubmit runs only after full-form validation succeeds.
Name input | Submit result
-----------------+---------------------------------
empty | Name is required.
51 characters | Name too long (50 character limit).
Taylor | HandleValidSubmit called
Enable generated validation for nested objects and booking items
Register AddValidation in the assembly that declares the booking model. The call registers validation services and activates a source generator, which produces metadata at build time. Put the root and child model types in a .cs file, not a Razor component, and mark the root with ValidatableType; the generator discovers reachable child types.
builder.Services.AddValidation();
The one-line registration works when the model and the call live in the same project. If models live in a separate assembly, put an extension there to run the source generator, then call that extension from the host before building the service provider. In this demo, the model and registration extension live in the eagerly loaded SharedModels assembly. The UI remains in the lazy-loaded BlazorDemoComponents assembly; calling its extension during host startup would fail because that assembly hasn't been loaded yet.
using Microsoft.Extensions.DependencyInjection;
namespace SharedModels;
public static class ValidationServiceCollectionExtensions
{
public static IServiceCollection AddSharedModelValidation(
this IServiceCollection services)
{
services.AddValidation();
return services;
}
}
The WebAssembly host calls the extension before building its service provider:
builder.Services.AddSharedModelValidation();
Add a reference to Microsoft.Extensions.Validation version 11.0.0 in the model project. In .NET 11, SkipValidation is no longer experimental; no experimental-API workaround or diagnostic suppression is needed for it.
Express booking and item rules in the model
Put the model in ValidationModels.cs in the same assembly as the registration call. These focused excerpts show the root model, its collection, and the item rules; the live demo contains the complete model. Initialize a DateTimeOffset from DateTime.Today, not DateTimeOffset.Today, which doesn't exist. The end-date method below demonstrates cross-property validation.
[ValidatableType]
public sealed class BookingValidationModel
{
[CustomValidation(typeof(BookingValidationModel), nameof(ValidateCustomer))]
public Guid CustomerId { get; set; }
[CustomValidation(typeof(BookingValidationModel), nameof(ValidateStart))]
public DateTimeOffset StartAt { get; set; } = new(DateTime.Today.AddDays(1).AddHours(9));
[CustomValidation(typeof(BookingValidationModel), nameof(ValidateEnd))]
public DateTimeOffset EndAt { get; set; } = new(DateTime.Today.AddDays(1).AddHours(10));
[CustomValidation(
typeof(BookingValidationModel), nameof(ValidateBookingItems))]
public List<BookingItemValidationModel> BookingItems { get; set; } =
[new()];
}
The full model also validates the room, notes, and each collection item. Its BookingItemValidationModel applies these rules to every item:
public sealed class BookingItemValidationModel
{
[Required]
public string? Name { get; set; }
[Range(1, 100, ErrorMessage = "Quantity must be between 1 and 100.")]
public int Quantity { get; set; }
[CustomValidation(
typeof(BookingItemValidationModel), nameof(ValidateStaff))]
public Guid StaffId { get; set; }
}
CustomValidation calls a static method when a built-in attribute doesn't express a rule. The customer, room, and staff checks reject Guid.Empty; a nonempty identifier alone does not prove that the selected record exists or is authorized. The list rule requires at least one item, while generated metadata enables validation of each item's properties.
public static ValidationResult? ValidateCustomer(Guid value) =>
value == Guid.Empty
? new("Customer is required.", [nameof(CustomerId)])
: ValidationResult.Success;
public static ValidationResult? ValidateBookingItems(
List<BookingItemValidationModel> value) =>
value.Count == 0
? new("At least one booking item is required.",
[nameof(BookingItems)])
: ValidationResult.Success;
ValidationContext.ObjectInstance gives the end-date rule access to the booking's start. Returning member names with ValidationResult associates errors with their fields. For a cross-field rule, changing the start alone doesn't guarantee that the end field is immediately revalidated: submit the form to recheck the complete model, or explicitly revalidate dependent fields in a production form.
public static ValidationResult? ValidateEnd(
DateTimeOffset value, ValidationContext context)
{
if (value == DateTimeOffset.MinValue)
return new("End date is required.", [nameof(EndAt)]);
var booking = (BookingValidationModel)context.ObjectInstance;
return booking.StartAt != DateTimeOffset.MinValue && value <= booking.StartAt
? new("End must be after Start.", [nameof(EndAt)])
: ValidationResult.Success;
}
Validate contact fields through the root model
Add an initialized Contact property to BookingValidationModel. These excerpts belong in SharedModels/ValidationModels.cs, alongside the existing rules; keep ValidatableType on the root.
// Inside BookingValidationModel:
[Required]
public BookingContactValidationModel Contact { get; set; } = new();
// Separate child class in the same file:
public sealed class BookingContactValidationModel
{
[Required(ErrorMessage = "Contact email is required.")]
[EmailAddress(ErrorMessage = "Enter a valid contact email.")]
public string? Email { get; set; }
[Required(ErrorMessage = "Contact phone is required.")]
[StringLength(20, MinimumLength = 6,
ErrorMessage = "Contact phone must be 6 - 20 characters.")]
public string? Phone { get; set; }
}
The child needs no ValidatableType attribute because the generator reaches it through the annotated root. Required on Contact rejects a null reference; it doesn't recursively validate the child's properties on its own. Generated metadata enables that traversal on whole-form submission.
Bind each contact message to the nested property, not the root's Contact reference. Insert this markup inside the booking EditForm, after its validator and summary:
<label for="contact-email">Email</label>
<InputText id="contact-email" @bind-Value="booking.Contact.Email" />
<ValidationMessage For="@(() => booking.Contact.Email)" />
<label for="contact-phone">Phone</label>
<InputText id="contact-phone" @bind-Value="booking.Contact.Phone" />
<ValidationMessage For="@(() => booking.Contact.Phone)" />
Submit with blank contact fields to see both required messages beside the inputs and in the summary. Then submit with not-an-email and phone 123 to see the format and length errors. Use taylor@example.com and 123456 to satisfy these rules; the phone rule checks length, not whether the number exists.
Skip lookup data without skipping actual booking items
Apply SkipValidation to AvailableItems on the root model. The attribute comes from Microsoft.Extensions.Validation, alongside ValidatableType; the rule attributes come from System.ComponentModel.DataAnnotations.
// Inside BookingValidationModel:
[SkipValidation]
public List<BookingItemValidationModel> AvailableItems { get; set; } = [];
This demo uses a list for lookup items and deliberately reuses BookingItemValidationModel so both collections have the same traversable item type: one is skipped, and the other is validated. A production catalogue can use a separate item view model. Its read-only catalogue preview contains this intentionally incomplete entry:
using SharedModels;
var booking = new BookingValidationModel
{
AvailableItems = [new() { Name = "Consultation" }]
};
// Lookup value defaults: Quantity = 0, StaffId = Guid.Empty.
This list is lookup-only: users don't edit it, and the demo doesn't submit it to a server. Generated validation skips the list and its items, so the incomplete catalogue entry doesn't block OnValidSubmit. Keep BookingItems validated: actual items still require a name, quantity from 1 to 100, and a staff selection.
SkipValidation is not a trust, sanitization, or security boundary. It doesn't remove data from serialization or exempt submitted data from server validation. In a real application, send only the intended booking data and independently validate it on the server.
BookingValidationModel
|-- CustomerId, RoomId, StartAt, EndAt, Notes
|-- Contact [Required] rejects null
| `-- Email, Phone child rules via generated traversal
|-- AvailableItems [SkipValidation]: no value traversal
`-- BookingItems list rule
`-- each item Name, Quantity, StaffId rules
Show collection and field errors in the booking form
Bind each message to the same model instance and property as its input. This focused excerpt shows a collection item; the complete runnable component, including the customer and date fields, is BookingValidationDemo.razor.
@using SharedModels
<EditForm Model="@booking" OnValidSubmit="@HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<ValidationMessage For="@(() => booking.BookingItems)" />
@foreach (var item in booking.BookingItems)
{
<div @key="item">
<InputText @bind-Value="item.Name" />
<ValidationMessage For="@(() => item.Name)" />
<InputNumber @bind-Value="item.Quantity" />
<ValidationMessage For="@(() => item.Quantity)" />
<InputSelect @bind-Value="item.StaffId">
<option value="@Guid.Empty">Select staff</option>
<option value="@staffId">Alex Kim</option>
</InputSelect>
<ValidationMessage For="@(() => item.StaffId)" />
</div>
}
<button type="submit">Save booking</button>
</EditForm>
Submit after adding or removing items to recheck the list and its contents. The local identifiers and the callback are illustrative: they don't load records or save a booking.
Input | Expected result on submit
--------------------------------+---------------------------------
No customer | Customer is required.
No booking items | At least one booking item is required.
Item quantity 0 | Quantity must be between 1 and 100.
End at or before start | End must be after Start.
Contact email empty | Contact email is required.
Contact email not-an-email | Enter a valid contact email.
Contact phone empty | Contact phone is required.
Contact phone 123 | Contact phone must be 6 - 20 characters.
Lookup quantity 0, no staff | No lookup errors (SkipValidation).
All editable fields valid | Booking passed validation.
The demo's success message records its last valid submission and remains visible after a later invalid submission; it doesn't indicate the form's current validity.
For framework details, see Microsoft's Blazor validation documentation.
Summary
- Use DataAnnotationsValidator and field messages for a simple form.
- Generate metadata from the root to validate nested contact fields and collection items; reachable children need no extra ValidatableType.
- Use CustomValidation for cross-property and collection rules.
- Use SkipValidation only for lookup-only data, never to bypass checks on actual booking items.
- Recheck dependent fields and enforce business rules independently on the server.
Next: Blazor WebAssembly forms.