Forms
TwForm
TwForm is a Blazor form that validates fields with data annotations and validators, shows an error summary and focuses the first error.
Last updated
Please be aware this component is new, may have bugs and/or be subject to change. Please report any bugs at
https://github.com/twblazor/twblazor/issues.
Validating a model
Give
TwForm a Model and bind each field to it with @bind-Value. The model's data annotations, such as [Required], are checked when the form is submitted and again as each field changes. A field with an error shows its message, and is marked invalid for screen readers. OnValidSubmit only runs once every field is valid.Error summary
Set
ShowSummary to list every error above the fields after a failed submit. Focus moves to the summary, so screen readers read it out, and each error is a link that moves focus to its field. Without a summary, focus moves to the first invalid field instead. Set FocusOnError="false" to leave focus where it is.Field validators
A field's own
Validator runs as it changes and again when the form is submitted, so it can stop the form submitting too. Use it for rules that don't belong on the model, or that need to look something up.Choices, dates and numbers
Every TwBlazor input takes part in validation, including radio groups, switches, sliders, ratings, and the date, time and color pickers. Bind each one with its own value parameter, for example
@bind-SelectedDate on a date picker.Validating from code
Call
ValidateAsync to check the form without submitting it, for example before moving to the next step of a wizard. IsValid holds the last result and IsModified says whether anything has changed.In an EditForm
TwBlazor fields also work in Blazor's own
EditForm, with DataAnnotationsValidator or any other validator. They show the form's messages and report every change, just as they do in a TwForm.Accessibility
The browser's own validation bubbles are turned off, because screen readers don't reliably announce them. Instead each invalid field is marked with
aria-invalid and its message is linked with aria-describedby and announced as it appears. After a failed submit, focus moves to the error summary or the first invalid field, so nobody is left on the submit button wondering what happened. Each summary error links to its field. Give every field a Label, and use Legend on radio groups.
Theme configuration
Styling is controlled by
TwBlazorTheme.Components (a TwFormTheme), configured via the
AddTwBlazor() options callback described on the Get Started page.
Every property is a set of Tailwind classes, so changes are picked up by your own Tailwind build.
| Property | Type | Controls |
|---|---|---|
Base |
string | |
Summary |
string | |
SummaryTitle |
string | |
SummaryList |
string | |
SummaryLink |
string |
Full reference: TwFormTheme on the API docs.