Text field

A text field component allows users to enter and edit single-line textual input. It serves as a fundamental building block for various form inputs in user interfaces

UsageCodeAccessibility
  <sl-text-field id="first-name" value="John" aria-label="First name"></sl-text-field>

When to use

The following guidance describes when to use the text field component.

Unique input

When users need to input information that is unique and cannot be anticipated from a predefined set of options. Text fields provide the flexibility to capture diverse and unpredictable data.

Single-line input

Text fields are ideal for capturing single-line responses.

When not to use

Text fields may not be the best choice in the following scenarios:

Sensitive information

For handling sensitive or confidential information, such as passwords or credit card numbers, it's advisable to utilize specialized secure input fields designed to obscure the entered data for enhanced security.

Longer text responses

Consider using a text area when you anticipate the input length will exceed the width of a text field or when you encourage users to provide longer text responses.

Anatomy

ItemNameDescriptionOptional
1ContainerAn input container is a structured enclosure for user input elements. It facilitates organized and user-friendly data collection in interfaces.no
2Input & Placeholder textInput text, entered by users, and placeholder text, providing guidance or examples.yes
3Validation iconEnsures input accuracy for users.yes

Figma Options

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

ItemOptionsDescription
Sizemd lgThe text field is available in two sizes. If not specified the default value is md (medium).
Variantdefault valid invalidWhen you're working on a scenario where you show what happens when a field is skipped or filled in incorrectly you can choose a different variant to show this.
Stateidle hover active disabledThese states are applied automatically in interactive examples or can be set explicitly when the use case asks for it. Default value is idle.
PlaceholderbooleanIf the setting is enabled, the placeholder will be visible, whereas if it is disabled, the user's input will be displayed. Default value is off.
Placeholder textvalueUse placeholder text to give the user a short hint about what they need to input (e.g. a sample value or a short description of the expected format). Placeholder is not a replacement for labels. It's an optional feature that disappears once users begin entering their data.
HintbooleanTo turn to hint on or off. Default value is off.
Input TextvalueWill be shown as the value of the text field
LabelvalueProvide users with additional context about button functionality by adding a label, ensuring clarity and ease of use.
Focus ringbooleanTurn the focus ring option to show the focus state of the text field. Default value is off.
  <sl-text-field id="last-name" aria-label="Last name" value="Smith"></sl-text-field>

API

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

Properties

NameAttributeTypeDefaultDescription
autocompleteautocompletetypeof HTMLInputElement.prototype.autocomplete | 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.
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.
maxLengthmaxlengthnumber | undefinedMaximum length (number of characters).
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-validbooleanfalseWhen set will cause the control to show it is valid after reportValidity is called.
showValidityshow-validity'valid' | 'invalid' | undefinedWhether to show the validity state.
sizesize'md' | 'lg''md'The size of the input.
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 value of the text field.

Methods

NameParametersReturnDescription
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.
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.
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.
formatValuevalue?: TstringMethod that formats the value and set's it on the native input element. Override this method
if you want to format the value in a different way.
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.
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.

Events

NameEvent typeDescription
sl-blurSlBlurEventEmits when the focus leaves the component.
sl-changeSlChangeEvent<T | undefined>Emits when the value changes.
sl-focusSlFocusEventEmits when the component gains focus.
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.

Slots

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

Keyboard interactions

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

CommandDescription
TabWhen focus is outside the text field, moves focus to the input container. If focus is on the input container, moves focus to the end enhancer (if provided, and interactive).

WAI-ARIA

WAI-ARIA Roles, States, and Properties for a text field provide essential information to assistive technologies and screen readers. They convey the text field's role, state, and additional properties to ensure accessibility and a better user experience for individuals using assistive technology.Specifies whether the attribute is always set in the component (no) or it can be provided by the developer (yes)

AttributeValueDescriptionUser supplied
role'textbox'Identifies as a text inputno
aria-labelstringDefines a string that labels the action that will be performed when the user interacts with the text field. Needs to be added when the text-field is not wrapped with sl-form-field and there is no sl-label.yes
aria-labelledbystringUsed to connect with single header/element that describes the text field, when there is no label component connected to.yes
aria-requiredbooleanInforms the user that an element is required. When set to ‘true’, screen readers notify users that the element is required.yes
aria-disabledbooleanAnnounces the text field component as disabled with a screen reader. See [Note 1] below.yes

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 text 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 text field out of the navigation flow.

When disabled is added to a text 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