FluentValidation
Build forms in Blazor using EditForm and FluentValidation.
In this guide, we will take a look at building forms with FluentValidation. We'll cover
building forms with the <Field /> component, adding validation rules with FluentValidation, error handling,
accessibility, and more.
Demo
We are going to build the following form. It has a simple text input and a textarea. On submit, we'll validate the form data and display any errors.
Approach
This form leverages Blazor's built-in forms and FluentValidation's rules. We'll build our form using the <Field /> component, which gives you complete flexibility over the markup and styling.
- Uses
EditFormandEditContextfor form state management. - A FluentValidation
AbstractValidatorfor the rules, kept apart from the model. - A small
FluentValidationValidatorcomponent that connects the validator to the form. <Field />components for building accessible forms.
Anatomy
Here's a basic example of a form using a value and change handler per control, and the <Field /> component.
<EditForm EditContext="_editContext" OnSubmit="Submit">
<FluentValidationValidator Validator="Validator" />
<Field data-invalid="@Invalid(() => _model.Title)">
<FieldLabel for="title">Bug Title</FieldLabel>
<Input id="title" Value="@_model.Title" ValueChanged="@(value => Change(() => _model.Title = value ?? ""))"
aria-invalid="@Invalid(() => _model.Title)" placeholder="Login button not working on mobile" autocomplete="off" />
<FieldDescription>Provide a concise title for your bug report.</FieldDescription>
<FieldError Errors="@Errors(() => _model.Title)" />
</Field>
</EditForm>Form
Install FluentValidation
dotnet add package FluentValidationAdd the validator component
Blazor ships DataAnnotationsValidator for attributes, but nothing for FluentValidation. This component plays the same
part: put it inside an EditForm and it runs your validator whenever the form validates.
@using System.Collections
@using System.Globalization
@using FluentValidation
@implements IDisposable
@code {
private EditContext? _editContext;
private ValidationMessageStore? _messages;
[CascadingParameter] private EditContext? CurrentEditContext { get; set; }
[Parameter, EditorRequired] public IValidator Validator { get; set; } = null!;
protected override void OnParametersSet()
{
if (CurrentEditContext is null)
{
throw new InvalidOperationException($"{nameof(FluentValidationValidator)} needs an EditContext: put it inside an EditForm.");
}
if (CurrentEditContext == _editContext)
{
return;
}
Detach();
_editContext = CurrentEditContext;
_messages = new ValidationMessageStore(_editContext);
_editContext.OnValidationRequested += Validate;
}
private void Validate(object? sender, ValidationRequestedEventArgs args)
{
if (_editContext is null || _messages is null)
{
return;
}
_messages.Clear();
var result = Validator.Validate(new ValidationContext<object>(_editContext.Model));
foreach (var failure in result.Errors)
{
_messages.Add(FieldFor(_editContext.Model, failure.PropertyName), failure.ErrorMessage);
}
_editContext.NotifyValidationStateChanged();
}
private static FieldIdentifier FieldFor(object model, string path)
{
var parts = path.Split('.');
var owner = model;
foreach (var part in parts[..^1])
{
owner = Member(owner, part) ?? owner;
}
return new FieldIdentifier(owner, parts[^1]);
}
private static object? Member(object owner, string part)
{
var bracket = part.IndexOf('[');
var name = bracket < 0 ? part : part[..bracket];
var value = owner.GetType().GetProperty(name)?.GetValue(owner);
if (bracket < 0 || value is not IList list)
{
return value;
}
var index = int.Parse(part[(bracket + 1)..^1], CultureInfo.InvariantCulture);
return index < list.Count ? list[index] : null;
}
private void Detach()
{
if (_editContext is not null)
{
_editContext.OnValidationRequested -= Validate;
}
}
public void Dispose() => Detach();
}Create a form model and its validator
We'll define the shape of our form with a plain class, and its rules with a FluentValidation validator.
@using FluentValidation
@code {
private sealed class BugReport
{
public string Title { get; set; } = "";
public string Description { get; set; } = "";
}
private sealed class BugReportValidator : AbstractValidator<BugReport>
{
public BugReportValidator()
{
RuleFor(report => report.Title)
.MinimumLength(5).WithMessage("Bug title must be at least 5 characters.")
.MaximumLength(32).WithMessage("Bug title must be at most 32 characters.");
RuleFor(report => report.Description)
.MinimumLength(20).WithMessage("Description must be at least 20 characters.")
.MaximumLength(100).WithMessage("Description must be at most 100 characters.");
}
}
}Set up the form
Next, we'll create an EditContext for the model, add the validator and handle the submit. The form's fields go inside the EditForm; we'll build them in the next step. Submit is where you'd use the values: here it shows them in a toast.
@inject ToastManager Toasts
<EditForm @key="_editContext" id="form-fluent-demo" EditContext="_editContext" OnSubmit="Submit">
<FluentValidationValidator Validator="Validator" />
...
</EditForm>
@code {
private static readonly BugReportValidator Validator = new();
private BugReport _model = new();
private EditContext _editContext = null!;
private bool _submitted;
protected override void OnInitialized() => _editContext = new EditContext(_model);
private void Submit()
{
_submitted = true;
if (_editContext.Validate())
{
Toasts.Add(new ToastOptions { Title = "You submitted the following values:", Description = JsonSerializer.Serialize(_model) });
}
}
}Build the form
We can now build the form using the <Field /> component. Each control takes its value from the model and writes
changes back through Change.
@using FluentValidation
@using System.Linq.Expressions
@using System.Text.Json
@inject ToastManager Toasts
<Card Class="w-full sm:max-w-md">
<CardHeader>
<CardTitle>Bug Report</CardTitle>
<CardDescription>Help us improve by reporting bugs you encounter.</CardDescription>
</CardHeader>
<CardContent>
<EditForm @key="_editContext" id="form-fluent-demo" EditContext="_editContext" OnSubmit="Submit">
<FluentValidationValidator Validator="Validator" />
<FieldGroup>
<Field data-invalid="@Invalid(() => _model.Title)">
<FieldLabel for="form-fluent-demo-title">Bug Title</FieldLabel>
<Input id="form-fluent-demo-title" Value="@_model.Title" ValueChanged="@(value => Change(() => _model.Title = value ?? ""))"
aria-invalid="@Invalid(() => _model.Title)" placeholder="Login button not working on mobile" autocomplete="off" />
<FieldError Errors="@Errors(() => _model.Title)" />
</Field>
<Field data-invalid="@Invalid(() => _model.Description)">
<FieldLabel for="form-fluent-demo-description">Description</FieldLabel>
<InputGroup>
<InputGroupTextarea id="form-fluent-demo-description" Value="@_model.Description" @oninput="@(e => Change(() => _model.Description = e.Value?.ToString() ?? ""))"
placeholder="I'm having an issue with the login button on mobile." rows="6"
Class="min-h-24 resize-none" aria-invalid="@Invalid(() => _model.Description)" />
<InputGroupAddon Align="InputGroupAddonAlign.BlockEnd">
<InputGroupText Class="tabular-nums">@_model.Description.Length/100 characters</InputGroupText>
</InputGroupAddon>
</InputGroup>
<FieldDescription>Include steps to reproduce, expected behavior, and what actually happened.</FieldDescription>
<FieldError Errors="@Errors(() => _model.Description)" />
</Field>
</FieldGroup>
</EditForm>
</CardContent>
<CardFooter>
<Field Orientation="FieldOrientation.Horizontal">
<Button Type="ButtonType.Button" Variant="ButtonVariant.Outline" @onclick="Reset">Reset</Button>
<Button Type="ButtonType.Submit" form="form-fluent-demo">Submit</Button>
</Field>
</CardFooter>
</Card>
@code {
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
private static readonly BugReportValidator Validator = new();
private BugReport _model = new();
private EditContext _editContext = null!;
private bool _submitted;
protected override void OnInitialized() => _editContext = new EditContext(_model);
private void Submit()
{
_submitted = true;
if (_editContext.Validate())
{
Toasts.Add(new ToastOptions
{
Title = "You submitted the following values:",
Description = JsonSerializer.Serialize(_model, Json),
});
}
}
private void Change(Action update)
{
update();
if (_submitted)
{
_editContext.Validate();
}
}
private void Reset()
{
_model = new BugReport();
_editContext = new EditContext(_model);
_submitted = false;
}
private IEnumerable<string> Errors(Expression<Func<object>> field) => _editContext.GetValidationMessages(field).Take(1);
private string Invalid(Expression<Func<object>> field) => Errors(field).Any() ? "true" : "false";
private sealed class BugReport
{
public string Title { get; set; } = "";
public string Description { get; set; } = "";
}
private sealed class BugReportValidator : AbstractValidator<BugReport>
{
public BugReportValidator()
{
RuleFor(report => report.Title)
.MinimumLength(5).WithMessage("Bug title must be at least 5 characters.")
.MaximumLength(32).WithMessage("Bug title must be at most 32 characters.");
RuleFor(report => report.Description)
.MinimumLength(20).WithMessage("Description must be at least 20 characters.")
.MaximumLength(100).WithMessage("Description must be at most 100 characters.");
}
}
}Done
That's it. You now have a fully accessible form with client-side validation.
When you submit the form, the Submit method will be called with the validated form data. If the form data is invalid, Blazor will display the errors next to each field.
Validation
Client-side Validation
FluentValidationValidator runs the validator you give it against the form's model. When the form is interactive, validation
runs in the browser's circuit (or WebAssembly) without a round trip to your API, and the same validator works on the server.
<EditForm EditContext="_editContext" OnSubmit="Submit">
<FluentValidationValidator Validator="Validator" />
...
</EditForm>Validation Modes
Blazor validates the whole model when you call EditContext.Validate() and a single field when you call EditContext.NotifyFieldChanged(). The examples here validate like this:
Change applies an update and, once the form has been submitted, revalidates it:
private void Change(Action update)
{
update();
if (_submitted)
{
_editContext.Validate();
}
}Displaying Errors
Display errors next to the field using <FieldError />. For styling and accessibility, set
data-invalid on the <Field /> component and aria-invalid on the form control.
<Field data-invalid="@Invalid(() => _model.Email)">
<FieldLabel for="email">Email</FieldLabel>
<Input id="email" Type="email" Value="@_model.Email" ValueChanged="@(value => Change(() => _model.Email = value ?? ""))"
aria-invalid="@Invalid(() => _model.Email)" />
<FieldError Errors="@Errors(() => _model.Email)" />
</Field>
@code {
private IEnumerable<string> Errors(Expression<Func<object>> field) => _editContext.GetValidationMessages(field).Take(1);
private string Invalid(Expression<Func<object>> field) => Errors(field).Any() ? "true" : "false";
}The attributes have to be the strings "true" and "false": the styles target data-[invalid=true] and aria-invalid. Errors returns only a field's first message, like a schema validator would.
Working with Different Field Types
Input
- Pass
ValueandValueChangedto the<Input />component. - To show errors, add the
aria-invalidattribute to the<Input />component and thedata-invalidattribute to the<Field />component.
<Field data-invalid="@Invalid(() => _model.Username)">
<FieldLabel for="form-fluent-input-username">Username</FieldLabel>
<Input id="form-fluent-input-username" Value="@_model.Username" ValueChanged="@(value => Change(() => _model.Username = value ?? ""))"
aria-invalid="@Invalid(() => _model.Username)" placeholder="blazix" autocomplete="username" />
<FieldDescription>This is your public display name. Must be between 3 and 10 characters. Must only contain letters, numbers, and underscores.</FieldDescription>
<FieldError Errors="@Errors(() => _model.Username)" />
</Field>Textarea
- Pass
ValueandValueChangedto the<Textarea />component.ValueChangedfires onchange; use@oninputfor live updates. - To show errors, add the
aria-invalidattribute to the<Textarea />component and thedata-invalidattribute to the<Field />component.
<Field data-invalid="@Invalid(() => _model.About)">
<FieldLabel for="form-fluent-textarea-about">More about you</FieldLabel>
<Textarea id="form-fluent-textarea-about" Value="@_model.About" @oninput="@(e => Change(() => _model.About = e.Value?.ToString() ?? ""))"
aria-invalid="@Invalid(() => _model.About)" placeholder="I'm a software engineer..." Class="min-h-[120px]" />
<FieldDescription>Tell us more about yourself. This will be used to help us personalize your experience.</FieldDescription>
<FieldError Errors="@Errors(() => _model.About)" />
</Field>Select
- Pass
ValueandValueChangedto the<Select />component. - To show errors, add the
aria-invalidattribute to the<SelectTrigger />component and thedata-invalidattribute to the<Field />component.
<Field Orientation="FieldOrientation.Responsive" data-invalid="@Invalid(() => _model.Language)">
<FieldContent>
<FieldLabel for="form-fluent-select-language">Spoken Language</FieldLabel>
<FieldDescription>For best results, select the language you speak.</FieldDescription>
<FieldError Errors="@Errors(() => _model.Language)" />
</FieldContent>
<Select Items="Items" Name="language" Value="@_model.Language" ValueChanged="@(value => Change(() => _model.Language = value ?? ""))">
<SelectTrigger id="form-fluent-select-language" aria-invalid="@Invalid(() => _model.Language)" Class="min-w-[120px]">
<SelectValue Placeholder="Select" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem Value="auto">Auto</SelectItem>
<SelectSeparator />
@foreach (var language in SpokenLanguages)
{
<SelectItem @key="language.Value" Value="@language.Value">@language.Label</SelectItem>
}
</SelectGroup>
</SelectContent>
</Select>
</Field>Checkbox
- For checkbox arrays, add or remove the item from the list in
CheckedChanged. - To show errors, add the
aria-invalidattribute to the<Checkbox />component and thedata-invalidattribute to the<Field />component. - Remember to add
data-slot="checkbox-group"to the<FieldGroup />component for proper styling and spacing.
<FieldSet data-invalid="@Invalid(() => _model.Tasks)">
<FieldLegend Variant="FieldLegendVariant.Label">Tasks</FieldLegend>
<FieldDescription>Get notified when tasks you've created have updates.</FieldDescription>
<FieldGroup data-slot="checkbox-group">
@foreach (var task in TaskOptions)
{
<Field @key="task.Id" Orientation="FieldOrientation.Horizontal" data-invalid="@Invalid(() => _model.Tasks)">
<Checkbox id="@($"form-fluent-checkbox-{task.Id}")" Name="tasks" aria-invalid="@Invalid(() => _model.Tasks)"
Checked="@_model.Tasks.Contains(task.Id)" CheckedChanged="@(value => Change(() => ToggleTask(task.Id, value)))" />
<FieldLabel for="@($"form-fluent-checkbox-{task.Id}")" Class="font-normal">@task.Label</FieldLabel>
</Field>
}
</FieldGroup>
</FieldSet>
<FieldError Errors="@Errors(() => _model.Tasks)" />
@code {
private void ToggleTask(string id, bool selected) =>
_model.Tasks = selected ? [.. _model.Tasks, id] : [.. _model.Tasks.Where(task => task != id)];
}Radio Group
- Pass
ValueandValueChangedto the<RadioGroup />component. - To show errors, add the
aria-invalidattribute to the<RadioGroupItem />component and thedata-invalidattribute to the<Field />component.
<FieldSet data-invalid="@Invalid(() => _model.Plan)">
<FieldLegend>Plan</FieldLegend>
<FieldDescription>You can upgrade or downgrade your plan at any time.</FieldDescription>
<RadioGroup Name="plan" Value="@_model.Plan" ValueChanged="@(value => Change(() => _model.Plan = value ?? ""))">
@foreach (var plan in Plans)
{
<FieldLabel @key="plan.Id" for="@($"form-fluent-radiogroup-{plan.Id}")">
<Field Orientation="FieldOrientation.Horizontal" data-invalid="@Invalid(() => _model.Plan)">
<FieldContent>
<FieldTitle>@plan.Title</FieldTitle>
<FieldDescription>@plan.Description</FieldDescription>
</FieldContent>
<RadioGroupItem Value="@plan.Id" id="@($"form-fluent-radiogroup-{plan.Id}")" aria-invalid="@Invalid(() => _model.Plan)" />
</Field>
</FieldLabel>
}
</RadioGroup>
<FieldError Errors="@Errors(() => _model.Plan)" />
</FieldSet>Switch
- Pass
CheckedandCheckedChangedto the<Switch />component. - To show errors, add the
aria-invalidattribute to the<Switch />component and thedata-invalidattribute to the<Field />component.
<Field Orientation="FieldOrientation.Horizontal" data-invalid="@Invalid(() => _model.TwoFactor)">
<FieldContent>
<FieldLabel for="form-fluent-switch-twoFactor">Multi-factor authentication</FieldLabel>
<FieldDescription>Enable multi-factor authentication to secure your account.</FieldDescription>
<FieldError Errors="@Errors(() => _model.TwoFactor)" />
</FieldContent>
<Switch id="form-fluent-switch-twoFactor" Name="twoFactor" Checked="@_model.TwoFactor"
CheckedChanged="@(value => Change(() => _model.TwoFactor = value))" aria-invalid="@Invalid(() => _model.TwoFactor)" />
</Field>Complex Forms
Here is an example of a more complex form with multiple fields and validation.
Resetting the Form
Replace the model and its EditContext to reset the form to its default values. Key the EditForm on the
context, so the form and its validator start over with it.
<EditForm @key="_editContext" EditContext="_editContext" OnSubmit="Submit">
...
</EditForm>
<Button Type="ButtonType.Button" Variant="ButtonVariant.Outline" @onclick="Reset">Reset</Button>
@code {
private void Reset()
{
_model = new BugReport();
_editContext = new EditContext(_model);
_submitted = false;
}
}Array Fields
A list in your model works for dynamic array fields. This is useful when you need to manage a variable number of fields, such as multiple email addresses or phone numbers.
Array Field Structure
Render the list with a @for loop and key each field on its item. Copy the index and the item into locals: the child content renders after the loop has finished, when index has moved on. The remove button goes at the end of the input group (see Removing Items).
<FieldSet Class="gap-4">
<FieldLegend Variant="FieldLegendVariant.Label">Email Addresses</FieldLegend>
<FieldDescription>Add up to 5 email addresses where we can contact you.</FieldDescription>
<FieldGroup Class="gap-4">
@for (var index = 0; index < _model.Emails.Count; index++)
{
var id = $"form-fluent-array-email-{index}";
var email = _model.Emails[index];
<Field @key="email" Orientation="FieldOrientation.Horizontal" data-invalid="@Invalid(() => email.Address)">
<FieldContent>
<InputGroup>
<InputGroupInput id="@id" Type="email" Value="@email.Address"
ValueChanged="@(value => Change(() => email.Address = value ?? ""))"
aria-invalid="@Invalid(() => email.Address)" placeholder="name@example.com" />
</InputGroup>
<FieldError Errors="@Errors(() => email.Address)" />
</FieldContent>
</Field>
}
</FieldGroup>
</FieldSet>Adding Items
Add an item to the list. Disable the button when you reach the limit.
<Button Type="ButtonType.Button" Variant="ButtonVariant.Outline" Size="ButtonSize.Sm"
@onclick="@(() => Change(() => _model.Emails.Add(new EmailAddress())))" Disabled="@(_model.Emails.Count >= 5)">
Add Email Address
</Button>Removing Items
Remove the item from the list. Only show the remove button when there's more than one item.
@if (_model.Emails.Count > 1)
{
<InputGroupAddon Align="InputGroupAddonAlign.InlineEnd">
<InputGroupButton Type="ButtonType.Button" Variant="ButtonVariant.Ghost" Size="InputGroupButtonSize.IconXs"
@onclick="@(() => Change(() => _model.Emails.Remove(email)))" aria-label="@($"Remove email {index + 1}")">
<svg>...</svg>
</InputGroupButton>
</InputGroupAddon>
}Array Validation
Use RuleForEach to validate each item. The validator component shows an item's messages next to its input, so
Errors(() => email.Address) finds them.
private sealed class ContactEmailsValidator : AbstractValidator<ContactEmails>
{
public ContactEmailsValidator()
{
RuleFor(contact => contact.Emails)
.NotEmpty().WithMessage("Add at least one email address.")
.Must(emails => emails.Count <= 5).WithMessage("You can add up to 5 email addresses.");
RuleForEach(contact => contact.Emails).ChildRules(email =>
email.RuleFor(e => e.Address).EmailAddress().WithMessage("Enter a valid email address."));
}
}