In Blazor, what do built-in input components such as InputText, InputNumber and InputDate add over a plain input element bound with @bind?
answer
- InputBase<TValue> underneath
- NotifyFieldChanged on every change
- valid, invalid, modified CSS classes
- ParsingErrorMessage and DisplayName
- name attribute for static posts
basics
~20 sThe Input components derive from InputBase<TValue> and join the cascaded EditContext: each change notifies it so validation runs, unparsable text becomes a validation message, and they render validity CSS classes, aria-invalid and a form-field name a plain input lacks.
solid answer
~40 s`InputText`, `InputNumber<T>`, `InputDate<T>`, `InputSelect<T>`, `InputCheckbox`, `InputTextArea`, `InputRadioGroup<T>` and `InputHidden` all derive from `InputBase<TValue>`. Inside an `EditForm` they pick up the cascaded `EditContext` and call `NotifyFieldChanged` on each change, so field validation runs. A value that does not parse, such as an emptied `InputNumber` bound to a non-nullable `int`, leaves the model unchanged and becomes a validation message ("The {0} field must be a number.", customizable through `ParsingErrorMessage`, with `{0}` filled from `DisplayName` or the property name). They render `valid`/`invalid` and `modified` CSS classes plus `aria-invalid`, and generate a `name` from the bind expression so static SSR posts map back. They require `@bind-Value` (a `ValueExpression`) and update on `change`, not on each keystroke.
code
razor · 17 lines<EditForm Model="Volunteer" FormName="volunteer-profile" OnValidSubmit="SaveAsync">
<DataAnnotationsValidator />
<InputDate @bind-Value="Volunteer.AvailableFrom" DisplayName="Available from" />
<InputNumber @bind-Value="Volunteer.HoursPerWeek"
ParsingErrorMessage="Enter whole hours for {0}." DisplayName="Hours per week" />
<InputSelect @bind-Value="Volunteer.Team">
@foreach (var team in Enum.GetValues<Team>())
{
<option value="@team">@team</option>
}
</InputSelect>
<InputCheckbox @bind-Value="Volunteer.HasFirstAidCertificate" />
<ValidationSummary />
<button type="submit">Save</button>
</EditForm>go deeper
Recall the main Input components and that they bind with @bind-Value inside an EditForm.
Explain InputBase's work: NotifyFieldChanged, parsing errors as messages, CSS classes, aria-invalid and generated field names.
Customize behaviour safely: ParsingErrorMessage and DisplayName, a FieldCssClassProvider, oninput variants and custom InputBase controls.
Set a team standard for form controls built on InputBase so validation, accessibility and static posting behave the same everywhere.
## The family Blazor's form inputs are components in `Microsoft.AspNetCore.Components.Forms`: | Component | Renders | Typical model type | |---|---|---| | `InputText` | `<input>` | `string` | | `InputTextArea` | `<textarea>` | `string` | | `InputNumber<TValue>` | `<input type="number">` | `int`, `long`, `short`, `float`, `double`, `decimal` and nullable forms | | `InputDate<TValue>` | `<input type="date">` by default; `Type` can be `DateTimeLocal`, `Month` or `Time` | `DateTime`, `DateOnly`, `TimeOnly`, `DateTimeOffset` | | `InputCheckbox` | `<input type="checkbox">` | `bool` | | `InputSelect<TValue>` | `<select>`, multiple when bound to an array | enum, string, numbers | | `InputRadioGroup<TValue>` with `InputRadio<TValue>` | a group of radio inputs | enum, string | | `InputHidden` | `<input type="hidden">` | `string` | All of them except the radio children derive from **`InputBase<TValue>`**, which is where the behaviour below lives. (`InputFile` is the odd one out: it is a plain `ComponentBase`.) ## What InputBase adds 1. **EditContext participation.** On first parameter set the component captures the cascaded `EditContext` and a `FieldIdentifier` built from `ValueExpression`. Every accepted change sets the value, raises `ValueChanged` and calls `EditContext.NotifyFieldChanged`, which is what triggers field validation and marks the field modified. 2. **Parsing with an error path.** Values travel through `CurrentValueAsString` and the abstract `TryParseValueFromString`. If parsing fails, the model keeps its old value, the component keeps the rejected string instead of reverting to the model's value so typing is not disrupted, and the message goes into a `ValidationMessageStore` the component owns. `InputNumber` and `InputDate` expose `ParsingErrorMessage`; `{0}` is replaced by `DisplayName` or, without one, the property name (so `ProductionDate` rather than `Production date`). 3. **State-driven CSS.** The default `FieldCssClassProvider` yields `valid` or `invalid`, prefixed with `modified` once the field changed; `EditContext.SetFieldCssClassProvider` swaps in other class names. 4. **Accessibility.** When the field has messages the component renders `aria-invalid="true"` (without overwriting a value you supplied) and removes it when they clear. 5. **A field name for static SSR.** The component renders a `name` attribute from its bind expression, such as `Volunteer.Email`, which is what lets a static form post map back through `[SupplyParameterFromForm]`. An explicit `name` attribute wins. 6. **Nullable support.** For `Nullable<T>`, an empty string maps to `null` instead of a parse error. ## Rules that trip people up - **`@bind-Value`, not `@bind`.** Two-way binding goes through the `Value`, `ValueChanged` and `ValueExpression` parameters; without a `ValueExpression` the component throws ("requires a value for the 'ValueExpression' parameter. Normally this is provided automatically when using 'bind-Value'"). - **Change, not input.** `InputText` and `InputNumber` update on the DOM `change` event, so the model and its validation catch up when the field loses focus. Per-keystroke updates need a custom component derived from `InputText` that binds `oninput`. - **Fixed EditContext.** An `InputBase` component throws if the cascaded `EditContext` changes while it lives; `EditForm` avoids this by recreating its children whenever its own context changes. - **Outside an EditForm.** The components still bind, but with no `EditContext` they validate nothing and show no state classes. ## Picking the component for each field A volunteer profile form shows how the choice follows the model type: - A name or email address: `InputText`, which keeps a `string`. - A free-text note about availability: `InputTextArea`. - Hours per week: `InputNumber<int>`, or `int?` when the field is optional so an empty box is `null` rather than a parse error. - The first available day: `InputDate<DateOnly>`; a shift start time: `InputDate<TimeOnly>` with `Type="InputDateType.Time"`. - Agreement to a code of conduct: `InputCheckbox`, bound to a `bool`. - A team chosen from an enum: `InputSelect<Team>`, or `InputRadioGroup<Team>` with one `InputRadio` per option when every choice should stay visible. - Several preferred tasks: `InputSelect<Duty[]>`, which renders `multiple` because the bound type is an array. - A record identifier the post must carry: `InputHidden`, remembering that a hidden field is still user-editable and must be checked on the server. ## Writing your own Deriving from `InputBase<TValue>` and overriding `TryParseValueFromString` gives a custom control, such as a phone-number box, the same participation for free.
- A user empties an InputNumber bound to a non-nullable int; what does the model hold and what does the user see?The empty string cannot become an `int`, so the model keeps its previous value. The component adds "The Hours per week field must be a number." (from `DisplayName`, or the property name) to its own message store, notifies the `EditContext`, and renders the `invalid` class with `aria-invalid`; `OnValidSubmit` is blocked until a number is entered. Bound to `int?`, the empty value would simply become `null`.
- Why does an InputText's validation message appear only after the user leaves the field, and how do you change that?`InputText` binds the DOM `change` event, which fires when the value is committed, typically on blur. Field validation follows that notification. For per-keystroke updates, derive a component from `InputText` that binds `oninput` instead; the rest of the `InputBase` behaviour is inherited.
- InputText works with @bind just like a plain input element.
- An emptied InputNumber bound to an int silently stores zero in the model.
- InputText updates the model on every keystroke by default.
- Input components validate on their own without an EditForm or EditContext.
- InputFile is an InputBase component with the same validation hooks.