Skip to content
GitHub11 stars

Data Annotations

Build forms in Blazor using EditForm and data annotations.

In this guide, we will take a look at building forms with Blazor's EditForm. We'll cover building forms with the <Field /> component, adding schema validation using data annotations, 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.

Bug Report
Help us improve by reporting bugs you encounter.
0/100 characters

Include steps to reproduce, expected behavior, and what actually happened.

@using System.ComponentModel.DataAnnotations
@using System.Linq.Expressions
@using System.Text.Json

Approach

This form leverages Blazor's built-in forms for flexible form handling. We'll build our form using the <Field /> component, which gives you complete flexibility over the markup and styling.

  • Uses EditForm and EditContext for form state management.
  • Data annotations (System.ComponentModel.DataAnnotations) and DataAnnotationsValidator for schema validation.
  • <Field /> components for building accessible forms.
  • Client-side validation in interactive render modes, with the same rules available on the server.

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">
    <DataAnnotationsValidator />
    <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

Create a form model

We'll start by defining the shape of our form using a class with data annotations.

BugReportForm.razor
@using System.ComponentModel.DataAnnotations

@code {
    private sealed class BugReport
    {
        [MinLength(5, ErrorMessage = "Bug title must be at least 5 characters.")]
        [MaxLength(32, ErrorMessage = "Bug title must be at most 32 characters.")]
        public string Title { get; set; } = "";

        [MinLength(20, ErrorMessage = "Description must be at least 20 characters.")]
        [MaxLength(100, ErrorMessage = "Description must be at most 100 characters.")]
        public string Description { get; set; } = "";
    }
}

Set up the form

Next, we'll create an EditContext for the model 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.

BugReportForm.razor
@inject ToastManager Toasts

<EditForm @key="_editContext" id="form-annotations-demo" EditContext="_editContext" OnSubmit="Submit">
    <DataAnnotationsValidator />
    ...
</EditForm>

@code {
    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.

BugReportForm.razor
@using System.ComponentModel.DataAnnotations
@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-annotations-demo" EditContext="_editContext" OnSubmit="Submit">
            <DataAnnotationsValidator />
            <FieldGroup>
                <Field data-invalid="@Invalid(() => _model.Title)">
                    <FieldLabel for="form-annotations-demo-title">Bug Title</FieldLabel>
                    <Input id="form-annotations-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-annotations-demo-description">Description</FieldLabel>
                    <InputGroup>
                        <InputGroupTextarea id="form-annotations-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-annotations-demo">Submit</Button>
        </Field>
    </CardFooter>
</Card>

@code {
    private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);

    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
    {
        [MinLength(5, ErrorMessage = "Bug title must be at least 5 characters.")]
        [MaxLength(32, ErrorMessage = "Bug title must be at most 32 characters.")]
        public string Title { get; set; } = "";

        [MinLength(20, ErrorMessage = "Description must be at least 20 characters.")]
        [MaxLength(100, ErrorMessage = "Description must be at most 100 characters.")]
        public string Description { get; set; } = "";
    }
}

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

DataAnnotationsValidator validates the model against its attributes. When the form is interactive, validation runs in the browser's circuit (or WebAssembly) without a round trip to your API.

<EditForm EditContext="_editContext" OnSubmit="Submit">
    <DataAnnotationsValidator />
    ...
</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:

ModeDescription
On submitThe first validation runs when the form is submitted, so untouched fields don't show errors.
On change, after submitOnce submitted, the form revalidates on every change, so errors clear as soon as they're fixed.

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 Value and ValueChanged to the <Input /> component.
  • To show errors, add the aria-invalid attribute to the <Input /> component and the data-invalid attribute to the <Field /> component.
Profile Settings
Update your profile information below.

This is your public display name. Must be between 3 and 10 characters. Must only contain letters, numbers, and underscores.

@using System.ComponentModel.DataAnnotations
@using System.Linq.Expressions
@using System.Text.Json
<Field data-invalid="@Invalid(() => _model.Username)">
    <FieldLabel for="form-annotations-input-username">Username</FieldLabel>
    <Input id="form-annotations-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 Value and ValueChanged to the <Textarea /> component. ValueChanged fires on change; use @oninput for live updates.
  • To show errors, add the aria-invalid attribute to the <Textarea /> component and the data-invalid attribute to the <Field /> component.
Personalization
Customize your experience by telling us more about yourself.

Tell us more about yourself. This will be used to help us personalize your experience.

@using System.ComponentModel.DataAnnotations
@using System.Linq.Expressions
@using System.Text.Json
<Field data-invalid="@Invalid(() => _model.About)">
    <FieldLabel for="form-annotations-textarea-about">More about you</FieldLabel>
    <Textarea id="form-annotations-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 Value and ValueChanged to the <Select /> component.
  • To show errors, add the aria-invalid attribute to the <SelectTrigger /> component and the data-invalid attribute to the <Field /> component.
Language Preferences
Select your preferred spoken language.

For best results, select the language you speak.

@using System.ComponentModel.DataAnnotations
@using System.Linq.Expressions
@using System.Text.Json
<Field Orientation="FieldOrientation.Responsive" data-invalid="@Invalid(() => _model.Language)">
    <FieldContent>
        <FieldLabel for="form-annotations-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-annotations-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-invalid attribute to the <Checkbox /> component and the data-invalid attribute to the <Field /> component.
  • Remember to add data-slot="checkbox-group" to the <FieldGroup /> component for proper styling and spacing.
Notifications
Manage your notification preferences.
Responses

Get notified for requests that take time, like research or image generation.

Tasks

Get notified when tasks you've created have updates.

@using System.ComponentModel.DataAnnotations
@using System.Linq.Expressions
@using System.Text.Json
<FieldSet data-invalid="@Invalid(() => _model.Tasks)">
    <FieldLegend Variant="FieldLegendVariant.Label">Tasks</FieldLegend>
    <FieldDescription>Get notified when tasks you&apos;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-annotations-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-annotations-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 Value and ValueChanged to the <RadioGroup /> component.
  • To show errors, add the aria-invalid attribute to the <RadioGroupItem /> component and the data-invalid attribute to the <Field /> component.
Subscription Plan
See pricing and features for each plan.
Plan

You can upgrade or downgrade your plan at any time.

@using System.ComponentModel.DataAnnotations
@using System.Linq.Expressions
@using System.Text.Json
<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-annotations-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-annotations-radiogroup-{plan.Id}")" aria-invalid="@Invalid(() => _model.Plan)" />
                </Field>
            </FieldLabel>
        }
    </RadioGroup>
    <FieldError Errors="@Errors(() => _model.Plan)" />
</FieldSet>

Switch

  • Pass Checked and CheckedChanged to the <Switch /> component.
  • To show errors, add the aria-invalid attribute to the <Switch /> component and the data-invalid attribute to the <Field /> component.
Security Settings
Manage your account security preferences.

Enable multi-factor authentication to secure your account.

@using System.ComponentModel.DataAnnotations
@using System.Linq.Expressions
@using System.Text.Json
<Field Orientation="FieldOrientation.Horizontal" data-invalid="@Invalid(() => _model.TwoFactor)">
    <FieldContent>
        <FieldLabel for="form-annotations-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-annotations-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.

You're almost there!
Choose your subscription plan and billing period.
Subscription Plan

Choose your subscription plan.

Choose how often you want to be billed.

Add-ons

Select additional features you'd like to include.

Advanced analytics and reporting

Automated daily backups

24/7 premium customer support

Receive email updates about your subscription

@using System.ComponentModel.DataAnnotations
@using System.Linq.Expressions
@using System.Text.Json

Resetting the Form

Replace the model and its EditContext to reset the form to its default values. Key the EditForm on the context, since DataAnnotationsValidator doesn't support a context that changes.

<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.

Contact Emails
Manage your contact email addresses.
Email Addresses

Add up to 5 email addresses where we can contact you.

@using System.ComponentModel.DataAnnotations
@using System.Linq.Expressions
@using System.Text.Json

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-annotations-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

DataAnnotationsValidator validates the list itself ([MinLength], [MaxLength]) but not its items. Validate the items with a ValidationMessageStore of your own.

@code {
    private static readonly EmailAddressAttribute EmailAttribute = new();

    private void CreateEditContext()
    {
        _editContext = new EditContext(_model);
        var messages = new ValidationMessageStore(_editContext);
        _editContext.OnValidationRequested += (_, _) =>
        {
            messages.Clear();
            foreach (var email in _model.Emails.Where(email => !EmailAttribute.IsValid(email.Address)))
            {
                messages.Add(() => email.Address, "Enter a valid email address.");
            }
        };
    }

    private sealed class ContactEmails
    {
        [MinLength(1, ErrorMessage = "Add at least one email address.")]
        [MaxLength(5, ErrorMessage = "You can add up to 5 email addresses.")]
        public List<EmailAddress> Emails { get; set; } = [new(), new()];
    }
}