Input

lightning:input

Represents interactive controls that accept user input depending on the type attribute.

For Aura components only. For LWC development, use lightning-input.

For Use In

Lightning Experience, Experience Builder Sites, Salesforce Mobile App, Lightning Out (Beta), Standalone Lightning App, Mobile Offline

A lightning:input component creates an HTML <input> element. This component supports the following input types:

  • checkbox
  • checkbox-button
  • date
  • datetime
  • time
  • email
  • file
  • password
  • search
  • tel
  • url
  • number
  • text (default)
  • toggle

The following HTML input types are not supported.

  • button
  • hidden
  • image
  • radio
  • reset
  • submit

Use lightning:button instead for input types button, reset, and submit.

Use lightning:radioGroup instead of input type radio for radio buttons.

If you’re creating forms to interact with Salesforce records, consider using lightning:recordForm or lightning:recordEditForm.

The label attribute is required. If you don’t want to display a label, specify the variant="label-hidden" attribute. See Accessibility for more information.

You can define a client-side controller action for input events like blur, focus, and change. For example, to handle a change event on the component when the value of the component is changed, use the onchange attribute. The component also provides a commit event, which the HTML <input> does not have. See Event Handling for details.

This component implements the input blueprint in the in the Salesforce Lightning Design System (SLDS).

Checkbox 

Checkboxes let you select one or more options. lightning:input type="checkbox" is useful for creating single checkboxes. If you are working with a group of checkboxes, use lightning:checkboxGroup instead.

1<lightning:input type="checkbox" label="Red" name="red" checked="true" />
2
3<lightning:input type="checkbox" label="Blue" name="blue" />

The checkbox implements the checkbox blueprint in SLDS.

A checkbox that’s disabled is grayed out and you can’t interact with it. A disabled checkbox isn’t focusable and isn’t submitted with the form. Similarly, you can’t interact with a read-only checkbox.

Read-Only Checkbox 

Unlike the native <input type="checkbox"> element, a read-only checkbox that you create using lightning:input with type="checkbox" and readonly="true" isn’t focusable. You can’t interact with a read-only checkbox and it isn’t submitted with the form. A read-only checkbox has these characteristics:

  • Displays a checkmark icon without an enclosing border when the checked attribute is used.
  • Displays a dotted square icon when the checked attribute isn’t used.

If the checkbox also has readonly="true" specified, adding required="true" to a checkbox has no effect.

The read-only checkbox implements the checkbox (view mode) blueprint in SLDS.

Indeterminate Checkbox 

An indeterminate checkbox shows a dash indicator instead of a checkbox. Use an indeterminate checkbox when you want to show a “Select All” checkbox for a group of checkbox. The indeterminate checkbox shows a dash indicator when only some items in a group are selected. Clicking the checkbox clears the indeterminate state. An indeterminate checkbox with a dash indicator has a checked value of false.

This example shows a “Select All” checkbox and a group of checkboxes. The “Select All” checkbox either selects or deselects all the checkboxes in the group. When all the checkboxes are selected and you deselect one of the checkboxes in the group, the “Select All” checkbox becomes an indeterminate checkbox that shows a dash indicator.

1<aura:component>
2  <aura:attribute name="allSelected" type="Boolean" default="false" />
3  <aura:attribute name="someSelected" type="Boolean" default="true" />
4  <aura:attribute name="selectedCount" type="Integer" default="1" />
5  <aura:attribute name="totalCount" type="Integer" default="3" />
6
7  <lightning:input
8    type="checkbox"
9    label="Select All"
10    checked="{! v.allSelected }"
11    indeterminate="{! v.someSelected }"
12    onchange="{! c.handleSelectAllChange }"
13  />
14
15  <div class="slds-var-m-top_small">
16    <lightning:input
17      type="checkbox"
18      label="Red"
19      name="color1"
20      value="red"
21      aura:id="colors"
22      onchange="{! c.handleItemChange }"
23    />
24    <lightning:input
25      type="checkbox"
26      label="Green"
27      name="color2"
28      value="green"
29      aura:id="colors"
30      checked="true"
31      onchange="{! c.handleItemChange }"
32    />
33    <lightning:input
34      type="checkbox"
35      label="Blue"
36      name="color3"
37      value="blue"
38      aura:id="colors"
39      onchange="{! c.handleItemChange }"
40    />
41  </div>
42
43  <p class="slds-var-m-top_small">
44    Selected: {! v.selectedCount } of {! v.totalCount }
45  </p>
46</aura:component>

The checkbox specifies true for the indeterminate boolean when the selected number of checkboxes is at least 1 but fewer than the total number of checkboxes in the group. In this scenario, only some checkboxes in the group are selected. After cmp.find returns the inputs, use get("v.checked") on each lightning:input to check if it’s selected.

1({
2  handleSelectAllChange: function (cmp, evt) {
3    var isChecked = evt.getSource().get("v.checked");
4    var items = cmp.find("colors");
5    items = Array.isArray(items) ? items : [items];
6    for (var i = 0; i < items.length; i++) {
7      items[i].set("v.checked", isChecked);
8    }
9    cmp.set("v.allSelected", isChecked);
10    cmp.set("v.someSelected", false);
11    cmp.set("v.totalCount", items.length);
12    cmp.set("v.selectedCount", isChecked ? items.length : 0);
13  },
14  handleItemChange: function (cmp, evt) {
15    var items = cmp.find("colors");
16    items = Array.isArray(items) ? items : [items];
17    var selectedCount = 0;
18    var totalCount = items.length;
19    for (var i = 0; i < items.length; i++) {
20      if (items[i].get("v.checked")) {
21        selectedCount++;
22      }
23    }
24    cmp.set("v.totalCount", totalCount);
25    cmp.set("v.selectedCount", selectedCount);
26    cmp.set("v.allSelected", totalCount > 0 && selectedCount === totalCount);
27    cmp.set("v.someSelected", selectedCount > 0 && selectedCount < totalCount);
28  },
29});

Checkbox-button 

Checkbox buttons let you select one or more options with an alternative visual design.

1<lightning:input
2  type="checkbox"
3  label="Add pepperoni"
4  name="addPepperoni"
5  checked="true"
6  value="pepperoni"
7/>
8<lightning:input
9  type="checkbox-button"
10  label="Add salami"
11  name="addSalami"
12  value="salami"
13/>

Color 

A color picker enables you to specify a color using a color picker or by entering the color into a text field.

1<lightning:input type="color" label="Color" name="color" value="#EEEEEE" />

Date 

A date input field includes a text input to type a date and a datepicker to select a date.

On mobile devices, this component uses the native datepicker, which ignores the date-style attribute. The native datepicker uses the user’s device settings for names of months and weekdays, the input date format, and the calendar type.

On desktop, this component uses a datepicker styled with the Lightning Design System. This picker uses the user’s Salesforce language setting for names of months and weekdays, and the user’s Salesforce locale setting for the date format. The entered date is validated against the user’s Salesforce locale format during the blur event.

The component uses dateStyle="medium" by default to display the date in a medium-length style, such as Jan 7, 2020 in the en-US locale. To display a short style such as 1/7/2020, set dateStyle="short". To display a long style such as January 7, 2020 set dateStyle="long".

When the field receives focus, a message appears under the field with the date format based on the user locale and dateStyle value. For example, if your user locale is en-US and the dateStyle is medium, the message displays “Format: Dec 31, 2024”.

The date entered must be valid for the user’s Salesforce locale, and match one of the short, medium, or long styles. If the date entered is valid, the component accepts the input and reformats it to the specified dateStyle during the blur event. For example, if the component specifies dateStyle="long" and you enter 1/7/2020 in the en-US locale, the component reformats it to January 7, 2020.

The component accepts a month value of 13 to accommodate conditions that sometimes require a 13th month in a year. For most locales, if you enter 13 for the month, the component converts the date to the first month of the following year during the blur event.

Use the value attribute to supply an initial value for the date as an ISO8601 formatted date string, such as 2020-11-03.

Set min and max to ISO8601 formatted date strings to limit the accepted date values.

  • If you set a min value, the datepicker calendar displays the month specified in the min value, and the previous month button is disabled. For example, if you specify min="2025-1-1", the calendar displays January 2025 and the previous month button is disabled.
  • If you set a max value, the datepicker calendar displays the month specified in the max value, and the next month button is disabled. For example, if you specify max="2025-12-31", the calendar displays December 2025 and the next month button is disabled.

The datepicker shows dates outside the min and max range in gray as a visual cue. Although users can select a date outside the range, the blur event triggers the field to display a validation error message. For a list of default error messages, see Error Messages. You can specify your own error messages for the min and max validation errors using the messageWhenRangeUnderflow and messageWhenRangeOverflow attributes.

You can guide users with a fieldLevelHelp tooltip and a placeholder prompt in the text field, as described in Adding Field-Level Help and Placeholder Text.

The datepicker calendar clips behind other components on the page if the parent container of lightning:input has a smaller width or height than the calendar. To prevent clipping, give the parent container a minimum width of 285px and minimum height of 310px.

1<lightning:input type="date" label="Birthday" name="date" />

Datetime 

A datetime field includes a text input to type a date and a datepicker to select a date, and similar fields for typing or picking a time.

The timepicker displays a dropdown menu with time options in 15-minute intervals, starting from 12:00 AM. To specify custom time intervals (in minutes) for the dropdown options, use the timeStepMinutes attribute. You can pass in an interval of 5 or more minutes.

On mobile devices, this component uses the native datetime picker, which ignores the dateStyle and timeStyle attributes. The native datetime picker uses the user’s device settings for names of months and weekdays, the input datetime format, and the calendar type.

On desktop, lightning:input provides its own date/time picker that’s styled with the Lightning Design System. Your Salesforce locale setting determines the acceptable date and time formats you can type in the fields and the format displayed in the fields after you pick a date and time. Your Salesforce language setting determines the names of months and weekdays displayed in the datepicker calendar, and the labels of the date and time fields.

The date and time you enter are automatically validated against your Salesforce locale format during the blur event. The date and time displayed reflect your Salesforce time zone setting. Use the timezone attribute to specify a different time zone in IANA time zone database format. For example, specify timezone="America/New_York" for US Eastern Time or timezone="GMT" for Greenwich Mean Time.

The component uses in dateStyle="medium" by default to display the date in a medium-length style, such as Jan 7, 2020 in the en-US locale. To display a short style such as 01/07/2020, set dateStyle="short" in the component. To display a long style such as January 7, 2020 set dateStyle="long".

When the field receives focus, a message appears under the field with the date format based on the user locale and dateStyle value. For example, if your user locale is en-US and the dateStyle is medium, the message displays “Format: Dec 31, 2024”.

The date entered must be valid for the user’s Salesforce locale, and match one of the short, medium, or long styles. If the date entered is valid, the component accepts the input and reformats it to the specified dateStyle during the blur event. For example, if the component specifies dateStyle="long" and a user enters 1/7/2020 in the en-US locale, the component reformats it to January 7, 2020.

The component accepts a month value of 13 to accommodate conditions that sometimes require a 13th month in a year. For most locales, if you enter 13 for the month, the component converts the date to the first month of the following year during the blur event.

The component uses timeStyle="short" by default to display the time without seconds, such as 6:53 PM in the en-US locale. To specify time including seconds, set timeStyle="medium" or timeStyle="long". The styles currently have the same formatting.

Use the value attribute to supply an initial value for the date and time as an ISO8601 formatted datetime string, such as 2020-11-03T18:13:41Z.

Set min and max to ISO8601 formatted datetime strings to limit the accepted date and time values.

  • If you set a min value, the datepicker calendar displays the month specified in the min value, and the previous month button is disabled. For example, if you specify min="2025-1-1", the calendar displays January 2025 and the previous month button is disabled.
  • If you set a max value, the datepicker calendar displays the month specified in the max value, and the next month button is disabled. For example, if you specify max="2025-12-31", the calendar displays December 2025 and the next month button is disabled.

The datepicker shows dates outside the min and max range in gray as a visual cue. Users can select a date and time outside the range, but the blur event triggers the field to display a validation error message. For a list of default error messages, see Error Messages. You can specify your own error messages using the messageWhenRangeUnderflow and messageWhenRangeOverflow attributes.

You can guide users with a fieldLevelHelp tooltip as described in Adding Field-Level Help and Placeholder Text.

On desktop, the datepicker calendar clips behind other components on the page if the parent container of lightning:input has a smaller width or height than the calendar. To prevent clipping, give the parent container a minimum width of 285px and minimum height of 310px.

In Lightning Experience, a datepicker calendar that’s opened overlays the record edit page or modal, the global header, and record form footer when scrolling.

Note: Set the same time zone on your mobile device and in Salesforce to avoid confusion and potential validation issues. For example, suppose the current time is 4:00 PM ET. Your mobile device is set to the America/New_York time zone and you’re interacting with Salesforce while it’s set to the America/Los_Angeles time zone. When you tap an empty date/time field on the mobile device, the native date/time picker automatically selects the current device time, 4:00 PM. Since the current time is 1:00 PM in Salesforce, this input time is in the future. If there’s a validation rule stating that the value must be earlier than the current time, for example, the value is invalid. This occurs only because of the time zone discrepancy, and only on mobile devices when the date/time field is initially empty.

1<lightning:input type="datetime" label="Created date" name="datetime" />

Email 

An input field for entering an email address. UTF-8 encoding is supported for international email addresses. Valid email addresses include name@example and name@example.com. The email pattern is automatically validated during the blur event.

1<lightning:input type="email" label="Email" />

To restrict email input to match a certain pattern, use the pattern attribute to specify a regular expression. For example, pass in pattern=".+@example.com" to accept an email address only from the domain example.com. When using pattern, you can provide a custom validation error message using the messageWhenPatternMismatch attribute.

You can also include a hint of what a user can enter using the placeholder attribute. The placeholder text is displayed on the field before a user enters an input, but it doesn’t validate input.

1<lightning:input
2  type="email"
3  label="Email"
4  pattern=".+@example.com"
5  placeholder="username@example.com"
6/>

To specify the maximum number of characters for an email address, use the maxlength attribute. When using maxlength, you can provide a custom validation error message using the messageWhenTooLong attribute.

1<lightning:input
2  type="email"
3  label="Email"
4  maxlength="50"
5  messageWhenTooLong="Your email address must not be more than 50 characters."
6/>

To specify the minimum number of characters for an email address, use the minlength attribute. When using minlength, you can provide a custom validation error message using the messageWhenTooShort attribute.

1<lightning:input
2  type="email"
3  label="Email"
4  maxlength="5"
5  messageWhenTooShort="Your email address must be more than 5 characters."
6/>

When multiple is used, the email field expects a single email address or a comma-separated list of email addresses. For example, my@example.com,your@example.com with or without a space after the comma.

1<lightning:input type="email" label="Email" multiple="true" />

File 

An input field for selecting files to upload using an Upload Files button or a drag-and-drop zone. This field accepts files up to 3.5 MB. To retrieve the list of selected files, use event.getSource().get("v.files");.

1<lightning:input
2  type="file"
3  label="Attachment"
4  name="file"
5  multiple="true"
6  accept="image/png, .zip"
7  onchange="{! c.handleFilesChange }"
8/>

Your selected files are returned in a FileList object containing a list of File objects with these attributes:

  • lastModified
  • lastModifiedDate
  • name
  • size

For more information on the File object, see MDN web docs: Getting information on selected files.

To handle file uploads in your org, wire up your component to an Apex controller that creates a ContentVersion and ContentVersionLink object.

Alternatively, use the lightning:fileUpload component for an integrated way to upload files to records.

To programmatically add a file, assign the file input to a FileList object, a File object, or an array of File objects. For example, you can add a new file to the files that are already attached.

1({
2  handleAttachFiles: function (cmp) {
3    var myFileField = cmp.find("inputFile");
4    var myFile = new File(["test content"], "test.txt", { type: "text/plain" });
5    myFileField.files = [...myFileField.files, myFile];
6  },
7});

To remove all files from the file list, use one of these methods.

1// Method 1: Clear files using DataTransfer
2myFileField.files = new DataTransfer().files;
3
4// Method 2: Clear files using an empty array
5myFileField.files = [];

Number 

An input field for entering a number. When working with numerical input, you can use attributes like max, min, and step.

The attributes maxlength, minlength, and pattern can’t be used with number type because they are for string data.

1<lightning:input type="number" name="number" label="Number" value="12345" />

To specify valid increments for numerical fields, use the step attribute. The value of step constrains the numbers that users can enter. If you don’t specify step, the default step value of 1 allows users to enter only integers.

To enable decimal number entry, specify a value for step that represents the number of decimal places accepted and the increment. For example, specifying step=".01" permits numbers such as 0.99 and 123456.78. Specifying step=".20" permits numbers such as 18.60 but not 18.61 or 18.70.

If a user enters a number that doesn’t match the step value, the browser flags it as invalid. Some browsers can round the number instead.

To format numerical input as a percentage or currency, set formatter to percent or currency respectively. To allow for decimal numbers, specify the step attribute as well.

1<lightning:input
2  type="number"
3  name="ItemPrice"
4  label="Price"
5  value="12345"
6  step=".01"
7  formatter="currency"
8/>

For the percent formatter, the entered number is multiplied by 100 on blur to display the percentage. For example, when you enter .75 the value displays as 75%. When you enter 1, the value displays as 100%.

To enter a percentage value as is, use formatter="percent-fixed". When you enter .75, the value displays as .75%, and when you enter 1, the value displays as 1%.

1<lightning:input
2  type="number"
3  name="decimal"
4  label="Enter a decimal value"
5  step="0.001"
6/>
7<lightning:input
8  type="number"
9  name="percentVal"
10  label="Enter a percentage value"
11  formatter="percent"
12  step="0.01"
13/>
14<lightning:input
15  type="number"
16  name="currencyVal"
17  label="Enter a dollar amount"
18  formatter="currency"
19  step="0.01"
20/>

Number formatting is based on the Intl.NumberFormat object and follows ISO guidelines, displaying a value based on the org currency and your Salesforce locale. For example, when using formatter="currency" step=".01", entering “123.45” displays “€123,45” if your org’s currency is set to EUR and your Salesforce locale is German. Your Salesforce locale is also used to determine if the number you entered is valid.

Number Validation 

The number field does not let you type invalid characters, although anything can be pasted in. When a field contains invalid characters, a default field-level error is displayed on blur and the value attribute returns an empty string. See the Input Validation and Error Messages sections for more information. Valid characters include digits, number shortcuts, exponential numbers, positive and negative signs, and decimal separators.

The lightning:input component uses the Javascript parseFloat() function to convert input value strings to numbers. Very large numbers with more than approximately 15 or 16 total digits can lose precision and appear to be rounded. Browsers can handle this loss of numeric precision differently, causing variation in decimal point rounding.

For example, parseFloat("12345678901234.12345") is stored in memory as 12345678901234.123, which appears rounded. The parsed value in memory is used for validation, not the entered number. As a result, a number that should be invalid can be accepted as valid due to the loss of precision in the stored value. If your lightning:input component sets step="0.0001", the entered value 12345678901234.12345 is invalid. However, the stored value 12345678901234.123 is valid, so the entered value is accepted.

Digits

Digits are the numbers 0 to 9. Invalid placement of 0’s are removed. For example, 010 results in 10. Trailing zeros after the decimal separator are also removed to match any given step pattern.

Number Shortcuts

Shortcuts such as k, K, m, and M are allowed. For the en-US locale, when you enter 1k the field displays 1,000. Entering 1m results in 1,000,000. When the input is focused, the input value is the multiplied number. For example, entering 1k results in 1,000 on blur, and 1000 when the input is focused again.

Shortcuts are not supported via the value attribute.

Exponential Numbers

The letter e or E is accepted when entering an exponential number. For example, when you enter 2e2 the field displays 200 on blur, and 2e2 when the input is focused again.

Positive and Negative Signs

Use + and - characters to represent positive and negative numbers. The positive + sign is removed on blur. If your number starts with +.> or -., 0 is added before the decimal separator. For example, entering +.2 results in 0.2 on blur.

Decimal Separators

Decimal separators are valid when you use the step attribute. Only the . and , decimal separators are allowed. If your number starts with a decimal separator, 0 is added before the decimal separator. For example, entering .2 results in 0.2 on blur.

Step

We recommend using a maximum of 9 decimal places for value and a maximum of 15 decimal places for step. Browsers exhibit inconsistencies in number calculation when you use more decimal places.

For example, a value of 9.9999999999 has more than 9 decimal places, and is interpreted as 10.0 by some browsers. If step is 0.01, stepMismatch validates as false when you enter 9.9999999999 because 10.0 matches the step.

Similar behavior occurs when step has a value such as 0.000000000000001, which is more than 15 decimal places.

Password 

An input field for entering a password. Characters you enter are masked.

1<lightning:input type="password" label="Password" name="password" />

Use the value attribute to optionally supply an initial value for the password. Use pattern to pass a regular expression to validate the password characters.

You can guide users with a fieldLevelHelp tooltip and a placeholder prompt in the password field, as described in Adding Field-Level Help and Placeholder Text.

Range 

A slider control for entering a number. When working with numerical input, you can use attributes like max, min, and step.

The attributes maxlength, minlength, and pattern can’t be used with range type because they are for string data.

1<lightning:input type="range" label="Number" name="number" min="0" max="10" />

Search 

An input field for entering a search string. This field displays the Lightning Design System search utility icon.

1<lightning:input type="search" label="Search" name="search" />

A search field that contains a value displays an X button to clear the search. Press the button to remove the value on the field. It also fires the blur, change, and commit events in that order.

When the Enter key is pressed, the search field fires the commit event. You can handle this event using the onkeydown handler.

To indicate activity in the search field with a spinner, such as data loading, use the isLoading attribute.

1<lightning:input type="search" label="Search" isLoading="true" />

When a search field is invalid, the field is displayed with a red border and a red search icon. However, an error icon isn’t displayed as it is for other input types.

Tel 

An input field for entering a telephone number. Use the pattern attribute to define a pattern for field validation.

1<lightning:input
2  type="tel"
3  label="Telephone"
4  name="tel"
5  value="343-343-3434"
6  pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
7/>

Text 

An input field for entering text. This is the default input type.

The value attribute for this input type only supports string values. To clear a text field by setting the value attribute, use "" to specify an empty string because null isn’t supported.

1<lightning:input label="Name" name="myname" />

Time 

A time field includes a text input to type a time and a timepicker to select a time.

On mobile devices, this component uses the native timepicker, which ignores the timeStyle attribute. The native timepicker uses the user’s device settings for the input time format.

On desktop, this component uses a timepicker styled with the Lightning Design System. This picker uses the user’s Salesforce locale setting for the time format, either 12-hr time with AM/PM or 24-hr time format. The entered date and time are validated against the user’s Salesforce locale format during the blur event.

By default, the timepicker renders above all modals and the main Salesforce header.

The component uses the attribute timeStyle="short" by default, so the timepicker displays time without seconds. To display time including seconds, set timeStyle="medium".

Use the value attribute to optionally supply an initial time as an ISO8601 formatted time string, such as 14:00:00.000.

Set min and max to ISO8601 formatted time strings to constrain the allowed time value. The time picker displays time values that are within the range only. If you type a time that’s outside the range, the blur event triggers the field to display a validation error message. For a list of default error messages, see Error Messages. You can specify your own error messages for the min and max validation errors using the messageWhenRangeUnderflow and messageWhenRangeOverflow attributes.

You can guide users with a fieldLevelHelp tooltip and a placeholder prompt in the text field, as described in Adding Field-Level Help and Placeholder Text.

1<lightning:input type="time" label="Closing time" name="time" />

The timepicker displays a dropdown menu with time options in 15-minute intervals, starting from 12:00 AM. To specify custom time intervals (in minutes) for the dropdown options, use the timeStepMinutes attribute. You can pass in an interval of 5 or more minutes.

1<lightning:input type="time" label="Time" timeStepMinutes="10" />

On mobile devices, this component uses the native timepicker, which ignores the timeStyle attribute. The native timepicker uses the user’s device settings for the input time format.

On desktop, this component uses a timepicker styled with the Lightning Design System. This picker uses the user’s Salesforce locale setting for the time format, either 12-hr time with AM/PM or 24-hr time format. The entered date and time are validated against the user’s Salesforce locale format during the blur event.

By default, the timepicker renders above all modals and the main Salesforce header.

The component uses the attribute timeStyle="short" by default, so the timepicker displays time without seconds. To display time including seconds, set timeStyle="medium".

Use the value attribute to optionally supply an initial time as an ISO8601 formatted time string, such as 14:00:00.000.

Set min and max to ISO8601 formatted time strings to constrain the allowed time value. The timepicker displays time values that are within the range only. If you type a time that’s outside the range, the blur event triggers the field to display a validation error message. For a list of default error messages, see Error Messages. You can specify your own error messages for the min and max validation errors using the messageWhenRangeUnderflow and messageWhenRangeOverflow attributes.

You can guide users with a fieldLevelHelp tooltip and a placeholder prompt in the text field, as described in Adding Field-Level Help and Placeholder Text.

Toggle 

A checkbox toggle for selecting one of two given values. Use the messageToggleActive and messageToggleInactive attributes to specify labels displayed under the toggle for each state. By default the labels are Active and Inactive. To omit labels, set these attributes to empty strings.

1<lightning:input
2  type="toggle"
3  label="Toggle value"
4  name="togglevalue"
5  checked="true"
6  messageToggleActive="On"
7  messageToggleInactive="Off"
8/>

By default, the toggle component expands to 100% of the available width. To limit the size of the toggle component, wrap it with an element that specifies the appropriate width.

1<aura:component>
2        <div style="width:fit-content">
3            <lightning:input type="toggle" label="Toggle value" name="togglevalue" checked="true" messageToggleActive="On" messageToggleInactive="Off"/>
4        <div/>
5</aura:component>

URL 

An input field for entering a URL. The address must include the protocol, such as http:// or ftp://. The URL pattern is automatically validated during the blur event. To enter the address without the protocol, such as www.example.com, use the default type="text" instead.

1<lightning:input type="url" label="Website" name="website" />

Input Validation 

Client-side input validation is available for this component. An invalid field is displayed with a red border and an error icon next to the field. An error message in red text is also displayed below the field. For example, an error message is displayed when a URL or email address is expected for an input type of url or email. Note that disabled and read-only inputs are always valid.

An error icon is displayed on fields that are in an invalid state for these input types.

  • email
  • number
  • password
  • range
  • tel
  • text
  • url

An error icon is displayed on fields, except on desktop browsers, for these input types.

  • date
  • datetime
  • datetime-local
  • time

You can define additional field requirements. For example, to set a maximum length, use the maxlength attribute.

1<lightning:input
2  name="quantity"
3  value="1234567890"
4  label="Quantity"
5  maxlength="10"
6/>

To check the validity states of an input, use the validity attribute, which is based on the Constraint Validation API. To determine if a field is valid, you can access the validity states in your client-side controller. Let’s say you have the following input field.

1<lightning:input
2  name="input"
3  aura:id="myinput"
4  label="Enter some text"
5  onblur="{! c.handleBlur }"
6/>

The validity attribute returns true for the valid property because all constraint validations are met, and in this case there are none.

1handleBlur: function (cmp, event) {
2    var validity = cmp.find("myinput").get("v.validity");
3    console.log(validity.valid); //returns true
4}

For example, you have the following form with several fields and a button. To display error messages on invalid fields, use the reportValidity() method.

1<aura:component>
2  <lightning:input
3    aura:id="field"
4    label="First name"
5    placeholder="First name"
6    required="true"
7  />
8  <lightning:input
9    aura:id="field"
10    label="Last name"
11    placeholder="Last name"
12    required="true"
13  />
14  <lightning:button
15    aura:id="submit"
16    type="submit"
17    label="Submit"
18    onclick="{! c.onClick }"
19  />
20</aura:component>

Validate the fields in the client-side controller.

1({
2  onClick: function (cmp, evt, helper) {
3    var allValid = cmp.find("field").reduce(function (validSoFar, inputCmp) {
4      inputCmp.reportValidity();
5      return validSoFar && inputCmp.checkValidity();
6    }, true);
7    if (allValid) {
8      alert("All form entries look valid. Ready to submit!");
9    } else {
10      alert("Please update the invalid form entries and try again.");
11    }
12  },
13});

This validity attribute is a read-only object with the following boolean properties. One property is set to true and the rest are false, depending on attributes set on the input field and the user’s entry.

  • badInput: Indicates that the value is invalid.
  • customError: Indicates that a custom error has been set. See Custom Validity Error Messages.
  • patternMismatch: Indicates that the value doesn’t match the specified pattern attribute for email, password, search, tel, text, or url input types.
  • rangeOverflow: Indicates that the value is greater than the specified max attribute for number, range, date, or datetime input types.
  • rangeUnderflow: Indicates that the value is less than the specified min attribute for number, range, date, or datetime input types.
  • stepMismatch: Indicates that the value doesn’t match the specified step attribute for number or range input types.
  • tooLong: Indicates that the value exceeds the specified maxlength attribute for email, password, search, tel, text, or url input types.
  • tooShort: Indicates that the value is less than the specified minlength attribute for email, password, search, tel, text, or url input types.
  • typeMismatch: Indicates that the value doesn’t match the required syntax for email or url input types.
  • valueMissing: Indicates that an empty value is provided when required attribute is set to true
  • valid: True if none of the preceding properties are true.

Error Messages 

When an input validation fails, a default message is displayed. You can provide your own values for the error messages to override the default messages. Specify your message using an attribute that corresponds to the validity error that’s returned, as shown in the following table.

ErrorDefault MessageAttribute to Override Default
badInputEnter a valid value.messageWhenBadInput
Your entry does not match the allowed format [locale's format]. (for types date, datetime, and time)
patternMismatchYour entry does not match the allowed pattern.messageWhenPatternMismatch
rangeOverflowThe number is too high.messageWhenRangeOverflow
Value must be [max] or earlier. (for types date, datetime, and time)
rangeUnderflowThe number is too low.messageWhenRangeUnderflow
Value must be [min] or later. (for types date, datetime, and time)
stepMismatchYour entry isn’t a valid increment.messageWhenStepMismatch
tooLongYour entry is too long.messageWhenTooLong
tooShortYour entry is too short.messageWhenTooShort
typeMismatchYou have entered an invalid format.messageWhenTypeMismatch
valueMissingComplete this field.messageWhenValueMissing
valueMissingComplete this field with format [locale's format]. (for types date, datetime, and time)

Note that the badInput validity error for date and datetime fields displays the default message depending on the locale. For example, “Your entry does not match the allowed format Dec 31, 2024” is displayed for en-US locale, but a different date format is shown for a different locale.

The valueMissing validity error for date and datetime displays “Complete this field with format [format]” where [format] is the date format that’s determined by the user locale. For example: “Complete this field with format Dec 31, 2024”

To override the default error message, use the corresponding attribute. For example, you have a text input with a minimum length of 5. If users enter fewer than 5 characters, the validity error returned is tooShort and the default message is “Your entry is too short.” Use the messageWhenTooShort attribute to display a different error message.

1<lightning:input
2  name="firstname"
3  label="First Name"
4  minlength="5"
5  messageWhenTooShort="Your entry must be at least 5 characters."
6/>

Custom errors that override the default error message are appended with the string “(Use format [format])” where [format] is the date format that’s determined by the user locale. For example, if your component sets badInput="This is a custom error", the displayed error for a date field in en-US locale is “This is a custom error (Use format Dec 31, 2024)”.

Custom Validity Error Messages 

The component supports setCustomValidity() from HTML5’s Constraint Validation API. To set an error message, provide a quoted string to display. To reset the error message, set the message to an empty string (""). See details at https://www.w3.org/TR/html52/sec-forms.html#dom-htmlinputelement-setcustomvalidity.

This example shows how to display a custom error message with setCustomValidity() and reportValidity(). The component is a simple text input with a button.

1<aura:component>
2  <lightning:input
3    aura:id="inputCmp"
4    label="Enter your name:"
5    name="fullName"
6  />
7  <lightning:button label="Register" onclick="{! c.register }" />
8</aura:component>

The client-side controller compares the input entered by the user to a particular text string. If true, setCustomValidity() sets the custom error message. The error message is displayed immediately using reportValidity(). Note that when the comparison isn’t true, you should set the error message to an empty string to zero out any messages that might have been set on previous calls.

1({
2  register: function (component, event) {
3    var inputCmp = component.find("inputCmp");
4    var value = inputCmp.get("v.value");
5    // is input valid text?
6    if (value === "John Doe") {
7      inputCmp.setCustomValidity("John Doe is already registered");
8    } else {
9      inputCmp.setCustomValidity(""); // if there was a custom error before, reset it
10    }
11    inputCmp.reportValidity(); // Tells lightning:input to show the error right away without needing interaction
12  },
13});

Using Autocomplete in Input Fields 

Some input types can be autofilled, based on your browser’s support of the feature. The autocomplete attribute passes through its value to the browser. These lightning:input types support the autocomplete attribute:

  • email
  • search
  • tel
  • text
  • url

The values on and off are supported, or a space-separated string of expected data types are supported, but the behavior depends on the browser. Some browsers might ignore the passed value.

To provide autocomplete guidance on the expected data type in the field, use a space-separated string that describes the meaning of the autocompletion value. For example autocomplete="shipping street-address". For more information, see the
MDN web docs for more information.

Adding Field-Level Help and Placeholder Text 

To provide a hint for entering information in the field, specify help text with the fieldLevelHelp attribute. For example, describe the characters required in a password input. Field level help adds an info icon next to the input label, with a tooltip displaying the specified help text.

To provide sample input in the field, use the placeholder attribute. For example, in a url input, show a URL in the correct format.

1<lightning:input
2  label="Event Name"
3  placeholder="Grand Opening"
4  fieldLevelHelp="The event name must be less than 50 characters"
5  maxlength="50"
6/>

fieldLevelHelp isn’t supported for file, toggle, and checkbox-button types.

placeholder is supported for date, email, number, password, search, tel, text, time, and url input types only. The placeholder support for date and time is a Salesforce addition and is not part of the HTML5 Standard. The placeholder text for date and time currently works only on desktop.

Event Handling 

The native HTML <input> element provides two events, input and change. The lightning:input component provides two custom events, change and commit.

The component’s change event behaves the same as the native input and change events together. It fires whenever you change the input value, as the HTML <input> element’s input event does. It also fires when you finish changing the input, as the <input> element’s change event does.

The component’s commit event fires only when you finish changing the input, which is the same behavior as the HTML <input> element’s change event.

The component doesn’t provide an input event because the behavior is provided in the change event.

To summarize, the component’s change event is equivalent to the input and change events of the <input> element. The component’s commit event is equivalent to the change event of the <input> element.

The change event fires at different times, depending on the specific input type. For information about the change event for the <input> element, see developer.mozilla.org.

See the Custom Events section in lightning-input documentation for more information about these events.

Handling Number Input 

In general, use oncommit to handle changes to number inputs. Use onchange for use cases where you want to process each character entered right away. For example, use onchange if you want to echo the content entered in another field as it is entered.

For input type number, the component sets the value to ” (an empty string) when the number input becomes invalid. The change event is fired each time the value changes, even when the value is set to an empty string. This enables you to reset the field in your onchange handler when input is invalid. Use separate variables to set the value of the number input and retrieve it.

Handling Selections 

When working with checkboxes and toggle switches, use aura:id to group and traverse the array of components. You can use get("v.checked") to determine which elements are checked or unchecked without reaching into the DOM. You can also use the name and value attributes to identify each component during the iteration.

The following example groups three checkboxes together using aura:id. The selected values are returned by clicking a button.

1<aura:component>
2  <aura:attribute name="selection" type="String" default="None" />
3  <fieldset>
4    <legend>Select a color:</legend>
5    <lightning:input
6      type="checkbox"
7      label="Red"
8      name="color1"
9      value="red"
10      aura:id="colors"
11    />
12    <lightning:input
13      type="checkbox"
14      label="Blue"
15      name="color2"
16      value="blue"
17      aura:id="colors"
18    />
19    <lightning:input
20      type="checkbox"
21      label="Green"
22      name="color3"
23      value="green"
24      aura:id="colors"
25    />
26  </fieldset>
27  <lightning:button label="Submit" onclick="{!c.submitForm}" />
28  <p>Checked items: {!v.selection}</p>
29</aura:component>

In your client-side controller, you can retrieve the array using cmp.find("colors") and inspect the checked values.

1({
2  submitForm: function (cmp, event, helper) {
3    var options = cmp.find("colors");
4    var result = [];
5    for (var i = 0; i < options.length; i++) {
6      if (options[i].get("v.checked")) {
7        result.push(options[i].get("v.value"));
8      }
9    }
10    cmp.set("v.selection", result.join(", "));
11  },
12});

Set and Read Selection Indexes 

The selectionStart and selectionEnd attribute values are passed through to the <input> element for input type text. The selectionStart value specifies the index of the first character selected in the input element, while the selectionEnd value specifies the index of the last character selected. Index values start at 0.

This example selects the characters from index 0 to the end when you click the button.

1<aura:component>
2  <aura:attribute name="textvalue" type="String" default="Initial value" />
3  <lightning:input
4    aura:id="myinput"
5    type="text"
6    value="{! v.textvalue }"
7    label="Enter some text"
8    onchange="{! c.handleChange}"
9  />
10  <lightning:button
11    aura:id="focus"
12    label="Focus selection"
13    onclick="{! c.handleClick }"
14  />
15</aura:component>

In the client-side controller, the selectionEnd property is set to the length of the current input value.

1({
2  handleChange: function (cmp, evt) {
3    let textvalue = cmp.get("v.textvalue");
4  },
5
6  handleClick: function (cmp, evt) {
7    let input = cmp.find("myinput");
8    let end = cmp.get("v.textvalue").length;
9    input.set("v.selectionStart", 0);
10    input.set("v.selectionEnd", end);
11    // Optionally, focus to highlight the selected characters
12    // input.focus();
13  },
14});

Design Guidelines 

For a single line of plain text input, use lightning:input. For multiple lines of plain text input, use lightning:textarea instead. For more specific input such as with numbers or email addresses, use the type attribute. Specifying type ensures that built-in validation can be applied to your data input.

In most contexts, a stacked label (standard or label-stacked variant) results in better readability and clarity. Use horizontal labels (label-inline variant) only if you need to save vertical real estate and have fewer than 10 fields.

To group related fields together, such as individual parts of an address, use compound input components like lightning:inputAddress or lightning:inputLocation. For name fields, use lightning:inputName.

Usage Considerations 

The label for an input field is displayed above the field by default. To display the label next to the field, use the label-inline variant.

maxlength limits the number of characters you can enter. The messageWhenTooLong error message isn’t triggered because you can’t type more than the number of characters allowed. However, you can use the messageWhenPatternMismatch and pattern attributes to trigger a message on blur when too many characters are entered.

1<lightning:input
2  type="text"
3  messageWhenPatternMismatch="Too many characters!"
4  pattern=".{0,5}"
5  name="input-name"
6  label="Enter up to 5 characters"
7/>

You can use custom labels that display translated values. For more information, see the Lightning Aura Components Developer Guide.

Accessibility 

You must provide a text label for accessibility to make the information available to assistive technology. The label attribute creates an HTML <label> element for your input component. To hide a label from view and make it available to assistive technology, use the label-hidden variant.

Specify the ariaLabelledby attribute and variant="label-hidden" to provide a custom label for assistive devices. Although the label attribute is still required, the <label> element is not rendered in this case.

1<p id="otherlabel">
2  Your Event Name
3  <lightning:input label="Event" variant="label-hidden" ariaLabelledby="otherlabel" />
4</p>

lightning:input sets the ariaInvalid attribute to match the validity state of the input field for assistive technology. If the validity attribute returns a true value for the valid property, then ariaInvalid is false. If the validity attribute returns a true value for any property other than valid, then ariaInvalid is true. When the component is initially loaded, ariaInvalid is set to false. This prevents fields that are marked required from being announced as invalid before you enter anything.

When a field-level error is displayed, lightning:input links the input field to the error message using the aria-describedby attribute, which enables assistive technology to announce the error message on the input field.

For the datetime type, the component renders two separate fields for date and time input. To provide accessibility features to the date field, use the dateAria* attributes. For example, use dateAriaDescribedBy to provide a descriptive label for the date field. To provide accessibility features to the time field, use the timeAria* attributes. For example, use timeAriaDescribedBy to provide a descriptive label for the time field.

In some cases, you can further improve the accessibility of your lightning:input implementation by specifying the autocomplete attribute. For supported types, see the Using Autocomplete in Input Fields section.

Use the autocomplete attribute to make it easier for a browser to prefill values in forms. For example, specify autocomplete="given-name" on lightning:input to expect the field value to be the user’s first name. The field displays a list of options that anticipates what a user is typing. The user presses the Down arrow key to select an option and press Enter. For more information, see WCAG 2.2: Using autocomplete attributes.

The autocomplete attribute is helpful for fields that specifically ask for data about the user who’s completing the form. Don’t use the autocomplete attribute on a field that asks for data about other people. The list of suggested values can come from past values entered by the user or they can be pre-configured on the user’s browser.

Attributes 

NameDescriptionTypeDefaultRequired
acceptSpecifies the types of files that the server accepts. Use this attribute with file input type only.String
ariaControlsA space-separated list of element IDs whose presence or content is controlled by the input.String
ariaDescribedByA space-separated list of element IDs that provide descriptive labels for the input.String
ariaErrorMessageA space-separated list of element IDs that provide descriptive error message for input.String
ariaInvalidA boolean value that controls whether assistive technologies read empty required textboxes as invalid. Default value is false.Boolean
ariaLabelDescribes the input to assistive technologies.String
ariaLabelledByA space-separated list of element IDs that provide labels for the input.String
autocompleteControls auto-filling of the field. Use this attribute with email, search, tel, text, and url input types only. Set the attribute to pass through autocomplete values to be interpreted by the browser.String
bodyThe body of the component. In markup, this is everything in the body of the tag.Aura.Component[]
checkedSpecifies whether the checkbox is checked. This value defaults to false.Booleanfalse
dateAriaControlsA space-separated list of element IDs whose presence or content is controlled by the date input when type='datetime'. On mobile devices, this is merged with ariaControls and timeAriaControls to describe the native date time input.String
dateAriaDescribedByA space-separated list of element IDs that provide descriptive labels for the date input when type='datetime'. On mobile devices, this is merged with ariaDescribedBy and timeAriaDescribedBy to describe the native date time input.String
dateAriaErrorMessageA space-separated list of element IDs that provide error messages for the date input when type='datetime'.String
dateAriaLabelDescribes the date input to assistive technologies when type='datetime'. On mobile devices, this label is merged with ariaLabel and timeAriaLabel to describe the native date time input.String
dateAriaLabelledByA space-separated list of element IDs that provide labels for the date input when type='datetime'. On mobile devices, this is merged with ariaLabelledBy and timeAriaLabelledBy to describe the native date time input.String
dateStyleThe display style of the date when type='date' or type='datetime'. Valid values are short, medium (default), and long. The format of each style is specific to the locale. On mobile devices this attribute has no effect.String
disabledSpecifies that an input element should be disabled. This value defaults to false.Booleanfalse
fieldLevelHelpHelp text detailing the purpose and function of the input. This attribute isn't supported for file, radio, toggle, and checkbox-button types.String
filesA FileList that contains selected files. Use this attribute with file input type only.Object
formatterString value with the formatter to be used for number input. Valid values include decimal, percent, percent-fixed, and currency.String
isLoadingFor the search type only. Specifies whether the spinner is displayed to indicate that data is loading. This value defaults to false.Booleanfalse
labelText label for the input.String
maxThe maximum acceptable value for the input. Use this attribute with number, range, date, time, and datetime input types only. For number and range type, the max value is a decimal number. For the date, time, and datetime types, the max value must use a valid string for the type.Object
maxlengthThe maximum number of characters allowed in the field. Use this attribute with email, password, search, tel, text, and url input types only.Integer
messageToggleActiveText shown for the active state of a toggle. The default is "Active".String{! $Label.LightningControl.activeCapitalized }
messageToggleInactiveText shown for then inactive state of a toggle. The default is "Inactive".String{! $Label.LightningControl.inactiveCapitalized }
messageWhenBadInputError message to be displayed when a bad input is detected. The badInput error can be returned for invalid input for any input type.String
messageWhenPatternMismatchError message to be displayed when a pattern mismatch is detected. The patternMismatch error can be returned when you specify a pattern for email, password, search, tel, text, or url input types.String
messageWhenRangeOverflowError message to be displayed when a range overflow is detected. The rangeOverflow error can be returned when you specify a max value for number or range input types.String
messageWhenRangeUnderflowError message to be displayed when a range underflow is detected. The rangeUnderflow error can be returned when you specify a min value for number or range input types.String
messageWhenStepMismatchError message to be displayed when a step mismatch is detected. The stepMismatch error can be returned when you specify a step value for number and range input types.String
messageWhenTooLongError message to be displayed when the value is too long. The tooLong error can be returned when you specify a max-length value for email, password, search, tel, text, and url input types.String
messageWhenTooShortError message to be displayed when the value is too short. The tooShort error can be returned when you specify a min-length value for email, password, search, tel, text, and url input types.String
messageWhenTypeMismatchError message to be displayed when a type mismatch is detected. The typeMismatch error can be returned for the email and url input types.String
messageWhenValueMissingError message to be displayed when the value is missing. The valueMissing error can be returned when you specify the required attribute for any input type.String
minThe minimum acceptable value for the input. Use this attribute with number, range, date, time, and datetime input types only. For number and range types, the min value is a decimal number. For the date, time, and datetime types, the min value must use a valid string for the type.Object
minlengthThe minimum number of characters allowed in the field. Use this attribute with email, password, search, tel, text, and url input types only.Integer
multipleSpecifies that a user can enter more than one value. Use this attribute with file and email input types only.Boolean
nameSpecifies the name of an input element.String
onchangeThe action triggered when a value attribute changes.Aura.Action
oncommitThe action triggered when the user finishes changing the input value. For example, pressing Enter, navigating away from the input element, clearing a search.action
patternSpecifies the regular expression that the input's value is checked against. Use this attribute with email, password, search, tel, text, and url input types only.String
placeholderText that is displayed when the field is empty, to prompt the user for a valid entry. Use this attribute with date, email, number, password, search, tel, text, time, and url input types only. Placeholder text isn't supported in date and time input types on mobile devices.String
readonlySpecifies that an input field is read-only. This value defaults to false.Booleanfalse
requiredSpecifies that an input field must be filled out before submitting the form. This value defaults to false.Booleanfalse
selectionEndSpecifies the index of the first character to select in the input element. This attribute is supported only for text type. Use with selectionStart to programmatically select a string.String
selectionStartSpecifies the index of the first character to select in the input element. This attribute is supported only for text type. Use with selectionEnd to programmatically select a string.String
stepGranularity of the value, specified as a positive floating point number. Use this attribute with number and range input types only. Use 'any' when granularity is not a concern. This value defaults to 1.Object
timeAriaControlsA space-separated list of element IDs whose presence or content is controlled by the time input when type='datetime'. On mobile devices, this is merged with ariaControls and dateAriaControls to describe the native date time input.String
timeAriaDescribedByA space-separated list of element IDs that provide descriptive labels for the time input when type='datetime'. On mobile devices, this is merged with ariaDescribedBy and dateAriaDescribedBy to describe the native date time input.String
timeAriaErrorMessageA space-separated list of element IDs that provide error messages for the time input when type='datetime'.String
timeAriaLabelDescribes the time input to assistive technologies when type='datetime'. On mobile devices, this label is merged with ariaLabel and dateAriaLabel to describe the native date time input.String
timeAriaLabelledByA space-separated list of element IDs that provide labels for the time input when type='datetime'. On mobile devices, this is merged with ariaLabelledBy and dateAriaLabelledBy to describe the native date time input.String
timeStyleThe display style of the time when type='time' or type='datetime'. Valid values are short (default), medium, and long. Currently, medium and long styles look the same. On mobile devices this attribute has no effect.String
timezoneSpecifies the time zone used when type='datetime' only. This value defaults to the user’s Salesforce time zone setting.String
typeThe type of the input. Valid values are checkbox, checkbox-button, color, date, datetime, time, email, file, password, range, search, tel, url, number, and toggle. This value defaults to text.Stringtext
validityRepresents the validity states that an element can be in, with respect to constraint validation.Object
valueSpecifies the value of an input element.Object
variantThe variant changes the appearance of an input field. Accepted variants include standard, label-inline, label-hidden, and label-stacked. This value defaults to standard, which displays the label above the field. Use label-hidden to hide the label but make it available to assistive technology. Use label-inline to horizontally align the label and input field. Use label-stacked to place the label above the input field.Stringstandard

Methods 

NameDescriptionArgument NameArgument TypeArgument Description
checkValidityReturns the valid property value (Boolean) on the ValidityState object to indicate whether the input has any validity errors.
reportValidityDisplay error messages if the input is invalid.
setCustomValiditySets a custom error message to be displayed when the input value is submitted.messageStringThe string that describes the error. If message is an empty string, the error message is reset.
showHelpMessageIfInvalidShows the help message if the form control is in an invalid state.