Number Field

A number field component allows users to enter and adjust numeric values.

UsageCodeAccessibility
<sl-number-field aria-label="Number field" step-buttons="end" value="100"></sl-number-field>

When to use

Easily Adjust Values

The stepper control buttons allow users to increment or decrement the value is defined in steps, within a well-defined, preferably small, range. They are ideal for scenarios like adjusting product amounts, setting measurement values, or tuning numeric settings where direct typing might lead to errors.

Require Formatting Values

Number fields can display format-specific information, such as currency symbols or percentage signs, alongside the input value. This visual formatting helps users recognise the context of the data they enter, improving clarity and reducing mistakes, especially in financial or statistical inputs.

When not to use

For a Fixed Number of Options

When the selection involves a small, predefined set of numeric options, the Select component is more suitable than a number field. Select ensure quicker selection, avoid invalid entries, and streamline the user experience for limited choices.

Anatomy

ItemNameDescriptionOptional
1Input fieldArea where users type the number.No
2Stepper controlsField buttons to increment or decrement the value.Yes
3LabelText describing the purpose of the field.Yes
4Helper textTrxt that provides extra guidance.Yes
5PrefixText placed before the value.Yes
6SuffixText placed after the value.Yes
7Error messageCommunicates validation issues.Yes

Variants

  • Basic: Input field only.
  • Steppers: Input field plus increment/decrement controls.
  • Prefix or Suffix: Adds contextual information like currency or units.
  • Hint text: Provides additional instructions.
  • Validation: Shows error messages when input rules are not respected.

States

  • Default: Active field allowing free numerical input and adjustments.
  • Hover: Highlighted field indicating interactivity before clicking.
  • Active: Field focused and ready for user input.

Figma Options

With these options, you can tweak the appearance of the number field in Figma. They are available in the Design Panel so you can compose the tag to exactly fit the user experience need for the use case you are working on.

ItemOptionsDescription
Sizemd lgSize 'md' is the default size of the number field component
VariantDefault Invalid disabledIndicates the state of the number field
Stateidle hover active disabledIndicates the state of the number field
LabelvalueThe text of the label
PlaceholadervalueThe text of the placeholder
SteppersEnd EdgesDefine the place of the stepper buttons
Imput TextvalueThe text of the value
FocusOn OffShows the focus ring
PrefixOn OffShows the prefix of the field
SufixOn OffShows the sufix of the field

Behaviours

Keyboard Input

The number field accepts direct keyboard input, allowing users to quickly enter numerical values without relying on other controls.

Stepper Controls

Users can adjust the value easily using the increment and decrement buttons, ensuring fine-grained control over numerical input.

Input Validation

The field validates user input based on minimum, maximum, and step settings to maintain consistent and valid data.

Visual Formatting

The number field can apply visual formatting, such as thousand separators, to improve readability and reduce entry errors.

Accessibility Support

Built with accessibility in mind, the number field uses ARIA roles and supports full keyboard navigation, ensuring an inclusive user experience.

  • Text Field: If you want a free-form text input.
  • Select: Selecting from predefined numeric options.
  <sl-number-field aria-label="Number field" placeholder="Type a number" value="20"></sl-number-field>

API

Number Field has a range of properties to define the experience in different use cases.

Properties

NameAttributeTypeDefaultDescription
autocompleteautocompletestring | undefinedSpecifies which type of data the browser can use to pre-fill the input.
customValiditycustom-validitystring | undefinedThe error message to display when the control is invalid.
dirty-booleanfalseA control is dirty if the user has changed the value in the UI.
disableddisabledboolean | undefinedWhether the text field is disabled; when set no interaction is possible.
form-HTMLFormElement | nullThe form associated with the control.
formValue-unknownThe value used when submitting the form.
formatOptionsformat-optionsIntl.NumberFormatOptions | undefinedNumber formatting options.
formattedValue-stringThe formatted value, to be used as the input value.
input-HTMLInputElementThe input element in the light DOM.
inputSizeinput-sizenumber | undefinedThe size attribute of the input element.
labels-`NodeListOf<HTMLLabelElement>` | nullThe labels associated with the control.
localelocalestringThe component's locale.
maxmaxnumber | undefinedInfinityThe maximum value that is acceptable and valid.
If the value is greater, the control will be invalid.
maxLengthmaxlengthnumber | undefinedMaximum length (number of characters).
minminnumber | undefined-InfinityThe minimum value that is acceptable and valid.
If the value is less, the control will be invalid.
minLengthminlengthnumber | undefinedMinimum length (number of characters).
namenamestring | undefinedThe name of the form control.
nativeFormValue-FormValueReturns the form value as used in a native `<form>`. This is always a string, File, FormData or null.
patternpatternstring | undefinedThis will validate the value of the input using the given pattern.
placeholderplaceholderstring | undefinedPlaceholder text in the input.
rawValue-string''The raw (string) value of the input.
readonlyreadonlyboolean | undefinedWhether you can interact with the input or if it is just a static, readonly display.
requiredrequiredboolean | undefinedWhether the text field is a required field.
showValidshow-validbooleanfalseOptional property to indicate the valid state should be shown.
showValidityshow-validity'valid' | 'invalid' | undefinedWhether to show the validity state.
sizesize'md' | 'lg' | undefinedmdThe size of the input.
stepstepnumber | undefined1The amount by which the value will be increased/decreased by a step up/down.
stepButtonsstep-buttons'end' | 'edges' | undefinedStep buttons placement for incrementing / decrementing. No step buttons by default.
touched-booleanfalseA control is marked touched once the user has triggered a blur event on it.
typetype'email' | 'number' | 'tel' | 'text' | 'url' | 'password''text'The input type. Only text types are valid here. For other types,
see their respective components.
valid-booleanReturns whether the form control is valid or not.
validationMessage-stringString representing a localized (by the browser) message that describes the validation
constraints that the control does not satisfy (if any). The string is empty if the control
is not a candidate for constraint validation, or it satisfies its constraints.

For true localization, see `getLocalizedValidationMessage()` instead.
validity-ValidityStateReturns the validity state the control is in.
validityState-'valid' | 'invalid' | 'pending'Returns the current validity state.
valuevalueunknown | undefinedThe text value.
valueAsNumbervalueAsNumberThe number value.

Methods

NameParametersReturnDescription
stepDowndecrement: numbervoidDecreases the current value by the `step` amount.
stepUpincrement: numbervoidIncreases the current value by the `step` amount.
onBlurvoidHandles the blur event when the input field loses focus.
Parses the raw value, validates the input, and updates the state.
reportValiditybooleanReturns whether the control is valid. If the control is invalid, calling this will
also cause an `invalid` event to be dispatched. After calling this, the control
will also report the validity to the user.
getLocalizedValidationMessagestringThis returns a localized validation message. It does not support all `ValidityState` properties,
since some require more context than we have here. If you need to support more, you can override
this method in your own form control.
setCustomValiditymessage: string | Promise<string>voidSets a custom validation message for the form control. If the message
is not an empty string, that will make the control invalid. By setting it to
an empty string again, you can make the control valid again.
renderPrefixTemplateResult | typeof nothingRenders the prefix slot; can be overridden to customize the prefix.
renderInputSlotTemplateResultRender the input slot; separate method so it is composable for child components.
renderSuffixTemplateResult | typeof nothingRenders the suffix slot; can be overridden to customize the suffix. Remember that if
you override this method, it will no longer automatically show the valid checkmark
when the input is valid.
parseValuevalue: stringT | undefinedMethod that converts the string value in the input to the specified type T. Override this method
if you want to convert the value in a different way. Throw an error if the value is invalid.
onFocusvoidHandles the focus event when the input field gains focus.
Emits a focus event and updates the focus ring state.
onInput{ target }: Event & { target: HTMLInputElement }voidHandles input events to update the raw and parsed values.
onKeydownevent: KeyboardEventvoidHandles the `keydown` event for the text field.
Simulates the native behavior of submitting a form when the Enter key is pressed.
onPrefixSlotChangeevent: Event & { target: HTMLSlotElement }voidHandles changes to the prefix slot. Detects and adds any `FieldButton` elements
assigned to the prefix slot to the `fieldButtons` state for further processing.
onSlotChangeevent: Event & { target: HTMLSlotElement }voidHandles changes to the input slot. Updates the `input` element reference
and synchronizes its attributes with the component's properties.
onSuffixSlotChangeevent: Event & { target: HTMLSlotElement }voidHandles changes to the suffix slot. Detects and adds any `FieldButton` elements
assigned to the suffix slot to the `fieldButtons` state for further processing.

Events

NameEvent typeDescription
sl-form-controlSlFormControlEventEmits when the form control is added to the DOM.
sl-update-stateSlUpdateStateEventEmits when the UI state (dirty, pristine, touched or untouched) of the form control changes.
sl-update-validitySlUpdateValidityEventEmits when the validity of the form control changes.
sl-validateSlValidateEventEmits when the form control can be validated.
sl-blurSlBlurEventEmits when the focus leaves the component.
sl-changeSlChangeEvent<T | undefined>Emits when the value changes.
sl-focusSlFocusEventEmits when the component gains focus.

Slots

NameDescription
prefixContent shown before the input
inputThe slot for the input element
suffixContent shown after the input

CSS Parts

NameDescription
wrapperThe input's wrapper

Keyboard interactions

Here's an overview of the common keyboard interactions associated with a number field:

CommandDescription
TabWhen focus is outside the number field, moves focus to the input container.
Arrow up/downIncreases or decreases the value in the number field, respecting the step attribute if set.

WAI-ARIA

In the component itself we use multiple aria-attributes to assure the component works well with a range of assistive technologies. For some attributes however it is not possible for the Design System to add a meaningfull value, because it relies on the context or way a component is used.

Attributes that we recommend you add in certain scenarios are mentioned below.

AttributeValueDescription
aria-labelstringDefines a string that tells the user what information they need to enter in this number field. Needs to be added when the number-field is not wrapped with sl-form-field and there is no sl-label.
aria-labelledbystringUsed to connect with single header/element that describes the number field, when there is no label component connected to.
aria-requiredbooleanInforms the user that an element is required. When set to ‘true’, screen readers notify users that the element is required. If there is already a required attribute added, it is recommended to avoid adding aria-required.
aria-disabledbooleanAnnounces the number field component as disabled with a screen reader. See [Note 1] below.

Notes:

  1. The aria-disabled should not be used as a one-for-one replacement for the disabled attribute because they have different functionalities:
  • disabled dims the number field visually, takes it out of the tab-focus sequence, prevents actions (click, enter) on it and announces it as 'dimmed' or 'disabled' in a screen reader.

  • aria-disabled only does the latter. You will need to disable the functionality yourself. This might be useful for scenarios where you don't want to take the number field out of the navigation flow.

When disabled is added to a number field there is no need to also add aria-disabled. Everything aria-disabled does, disabled does as well. You can read more on the difference and in which scenarios which option might be preferable on the MDN page about aria-disabled.

Interactive example