: The HTML Input element - HTML | MDN
Skip to search
: The HTML Input element
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
* Some parts of this feature may have varying levels of support.
See full compatibility
Report feedback
The
HTML
element is used to create interactive controls for web-based forms in order to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and
user agent
. The
element is one of the most powerful and complex in all of HTML due to the sheer number of combinations of input types and attributes.
Try it
type="text"
id="name"
name="name"
required
minlength="4"
maxlength="8"
size="10" />
label {
display: block;
font:
1rem "Fira Sans",
sans-serif;
input,
label {
margin: 0.4rem 0;
types
How an
works varies considerably depending on the value of its
type
attribute, hence the different types are covered in their own separate reference pages. If this attribute is not specified, the default type adopted is
text
The available types are as follows:
Type
Description
Basic Examples
button
A push button with no default behavior displaying the value of the
value
attribute, empty by default.
checkbox
A check box allowing single values to be selected/deselected.
color
A control for specifying a color; opening a color picker when active in supporting browsers.
date
A control for entering a date (year, month, and day, with no time).
Opens a date picker or numeric wheels for year, month, day when active
in supporting browsers.
datetime-local
A control for entering a date and time, with no time zone. Opens a date
picker or numeric wheels for date- and time-components when active in supporting browsers.
email
A field for editing an email address. Looks like a
text
input, but has validation parameters and relevant
keyboard in supporting browsers and devices with dynamic keyboards.
file
A control that lets the user select a file.
Use the
accept
attribute to define the types of files that the control can select.
hidden
A control that is not displayed but whose value is submitted to the
server. There is an example in the next column, but it's hidden!
image
A graphical
submit
button. Displays an image defined by the
src
attribute.
The
alt
attribute displays if the image
src
is missing.
month
A control for entering a month and year, with no time zone.
number
A control for entering a number. Displays a spinner and adds default
validation. Displays a numeric keypad in some devices
with dynamic keypads.
password
A single-line text field whose value is obscured.
Will alert user if site is not secure.
radio
A radio button, allowing a single value to be selected out of multiple choices with the same
name
value.
range
A control for entering a number whose exact value is not important.
Displays as a range widget defaulting to the middle value.
Used in conjunction
min
and
max
to define the range of acceptable values.
reset
A button that resets the contents of the form to default values. Not recommended.
A single-line text field for entering search strings. Line-breaks are
automatically removed from the input value. May include a delete icon in
supporting browsers that can be used to clear the field. Displays a
search icon instead of enter key on some devices with dynamic keypads.
submit
A button that submits the form.
tel
A control for entering a telephone number. Displays a telephone keypad
in some devices with dynamic keypads.
text
The default value. A single-line text field. Line-breaks are
automatically removed from the input value.
time
A control for entering a time value with no time zone.
url
A field for entering a URL. Looks like a
text
input, but
has validation parameters and relevant keyboard in supporting browsers
and devices with dynamic keyboards.
week
A control for entering a date consisting of a week-year number and a week number with no time zone.
Obsolete values
datetime
Deprecated
A control for entering a date and time (hour, minute, second, and fraction of a second) based on UTC time zone.
Attributes
The
element is so powerful because of its attributes; the
type
attribute, described with examples above, being the most important. Since every
element, regardless of type, is based on the
HTMLInputElement
interface, they technically share the exact same set of attributes. However, in reality, most attributes have an effect on only a specific subset of input types. In addition, the way some attributes impact an input depends on the input type, impacting different input types in different ways.
This section provides a table listing all the attributes with a brief description. This table is followed by a list describing each attribute in greater detail, along with which input types they are associated with. Those that are common to most or all input types are defined in greater detail below. Attributes that are unique to particular input types—or attributes which are common to all input types but have special behaviors when used on a given input type—are instead documented on those types' pages.
Attributes for the
element include the
global HTML attributes
and additionally:
Attribute
Type(s)
Description
accept
file
Hint for expected file type in file upload controls
alpha
color
Opacity of the color
alt
image
alt attribute for the image type. Required for accessibility
autocapitalize
all except
url
email
, and
password
Controls automatic capitalization in inputted text.
autocomplete
all except
checkbox
radio
, and buttons
Hint for form autofill feature
capture
file
Media capture input method in file upload controls
checked
checkbox
radio
Whether the command or control is checked
colorspace
color
The
color space
that should be used for selecting the color value
dirname
hidden
text
url
tel
email
Name of form field to use for sending the element's directionality in form submission
disabled
all
Whether the form control is disabled
form
all
Associates the control with a form element
formaction
image
submit
URL to use for form submission
formenctype
image
submit
Form data set encoding type to use for form submission
formmethod
image
submit
HTTP method to use for form submission
formnovalidate
image
submit
Bypass form control validation for form submission
formtarget
image
submit
Browsing context for form submission
height
image
Same as height attribute for
; vertical dimension
list
all except
hidden
password
checkbox
radio
, and buttons
Value of the id attribute of the
let guestName = form.elements.guest;
let hatSize = form.elements["hat-size"];
When this code has run,
guestName
will be the
HTMLInputElement
for the
guest
field, and
hatSize
the object for the
hat-size
field.
Warning:
Avoid giving form elements a
name
that corresponds to a built-in property of the form, since you would then override the predefined property or method with this reference to the corresponding input.
pattern
Valid for
text
url
tel
email
, and
password
, the
pattern
attribute is used to compile a regular expression that the input's
value
must match in order for the value to pass
constraint validation
. It must be a valid JavaScript regular expression, as used by the
RegExp
type, and as documented in our
guide on regular expressions
. No forward slashes should be specified around the pattern text. When compiling the regular expression:
the pattern will be implicitly wrapped with
^(?:
and
)$
, such that the match is required against the
entire
input value, i.e.,
^(?:
the
'v'
flag is specified so that the pattern is treated as a sequence of Unicode code points, instead of as
ASCII
If the
pattern
attribute is present but is not specified or is invalid, no regular expression is applied and this attribute is ignored completely. If the pattern attribute is valid and a non-empty value does not match the pattern, constraint validation will prevent form submission. If the
multiple
is present, the compiled regular expression is matched against each comma separated value.
Note:
If using the
pattern
attribute, inform the user about the expected format by including explanatory text nearby. You can also include a
title
attribute to explain what the requirements are to match the pattern; most browsers will display this title as a tooltip. The visible explanation is required for accessibility. The tooltip is an enhancement.
See
Client-side validation
for more information.
placeholder
Valid for
text
url
tel
email
password
, and
number
, the
placeholder
attribute provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that provides a hint as to the expected type of data, rather than an explanation or prompt. The text
must not
include carriage returns or line feeds. So for example if a field is expected to capture a user's first name, and its label is "First Name", a suitable placeholder might be "e.g., Mustafa".
Note:
The
placeholder
attribute is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See
Labels
for more information.
popovertarget
Turns an
element into a popover control button; takes the ID of the popover element to control as its value. See the
Popover API
landing page for more details. Establishing a relationship between a popover and its invoker button using the
popovertarget
attribute has two additional useful effects:
The browser creates an implicit
aria-details
and
aria-expanded
relationship between popover and invoker, and places the popover in a logical position in the keyboard focus navigation order when shown. This makes the popover more accessible to keyboard and assistive technology (AT) users (see also
Popover accessibility features
).
The browser creates an implicit anchor reference between the two, making it very convenient to position popovers relative to their controls using
CSS anchor positioning
. See
Popover anchor positioning
for more details.
popovertargetaction
Specifies the action to be performed on a popover element being controlled by a control
. Possible values are:
"hide"
The button will hide a shown popover. If you try to hide an already hidden popover, no action will be taken.
"show"
The button will show a hidden popover. If you try to show an already showing popover, no action will be taken.
"toggle"
The button will toggle a popover between showing and hidden. If the popover is hidden, it will be shown; if the popover is showing, it will be hidden. If
popovertargetaction
is omitted,
"toggle"
is the default action that will be performed by the control button.
readonly
A Boolean attribute which, if present, indicates that the user should not be able to edit the value of the input. The
readonly
attribute is supported by the
text
url
tel
email
date
month
week
time
datetime-local
number
, and
password
input types.
See the
HTML attribute:
readonly
for more information.
required
required
is a Boolean attribute which, if present, indicates that the user must specify a value for the input before the owning form can be submitted. The
required
attribute is supported by
text
url
tel
email
date
month
week
time
datetime-local
number
password
checkbox
radio
, and
file
inputs.
See
Client-side validation
and the
HTML attribute:
required
for more information.
size
Valid for
email
password
tel
url
, and
text
, the
size
attribute specifies how much of the input is shown. Basically creates same result as setting CSS
width
property with a few specialties. The actual unit of the value depends on the input type. For
password
and
text
, it is a number of characters (or
em
units) with a default value of
20
, and for others, it is pixels (or
px
units). CSS
width
takes precedence over the
size
attribute.
src
Valid for the
image
input button only, the
src
is string specifying the URL of the image file to display to represent the graphical submit button. See the
image
input type.
step
Valid for
date
month
week
time
datetime-local
number
, and
range
, the
step
attribute is a number that specifies the granularity that the value must adhere to. Only values which are a whole number of steps from the step base are valid. The step base is
min
if specified,
value
otherwise, or
if neither is provided (except for
week
, which has a default step base of −259,200,000, representing the start of week
1970-W01
).
If not explicitly included:
step
defaults to 1 for
number
and
range
Each date/time input type has a default
step
value appropriate for the type; see the individual input pages:
date
datetime-local
month
time
, and
week
The value must be a positive number—integer or float—or the special value
any
, which means no stepping is implied, and any value is allowed (barring other constraints, such as
min
and
max
).
For example, if you have
, then any even integer,
10
or greater, is valid. If omitted,
, any integer is valid, but floats (like
4.2
) are not valid, because
step
defaults to
. For
4.2
to be valid,
step
would have had to be set to
any
, 0.1, 0.2, or the
min
value would have had to be a number ending in
.2
, such as
Note:
When the data entered by the user doesn't adhere to the stepping configuration, the value is considered invalid in constraint validation and will match the
:invalid
pseudoclass.
See
Client-side validation
for more information.
switch
Experimental
Non-standard
Valid for
checkbox
input only,
switch
is a Boolean attribute that indicates whether the checkbox input should be rendered as a switch.
Note:
This attribute is still experimental and has limited browser support. The attribute is ignored on unsupported browsers.
tabindex
Global attribute valid for all elements, including all the input types, an integer attribute indicating if the element can take input focus (is focusable), if it should participate to sequential keyboard navigation. As all input types except for input of type hidden are focusable, this attribute should not be used on form controls, because doing so would require the management of the focus order for all elements within the document with the risk of harming usability and accessibility if done incorrectly.
title
Global attribute valid for all elements, including all input types, containing a text representing advisory information related to the element it belongs to. Such information can typically, but not necessarily, be presented to the user as a tooltip. The title should NOT be used as the primary explanation of the purpose of the form control. Instead, use the
/* matches a form control whose valid values are limited to a range of values */
input[min][max] {
/* matches a form control with a pattern attribute */
input[pattern] {
::placeholder
By default, the appearance of placeholder text is a translucent or light gray. The
::placeholder
pseudo-element is the input's
placeholder
text
. It can be styled with a limited subset of CSS properties.
css
::placeholder {
color: blue;
Only the subset of CSS properties that apply to the
::first-line
pseudo-element can be used in a rule using
::placeholder
in its selector.
caret-color
A property specific to text entry-related elements is the CSS
caret-color
property, which lets you set the color used to draw the text input caret:
HTML
html
CSS
css
input.custom {
caret-color: red;
font:
16px "Helvetica",
"Arial",
sans-serif;
Result
field-sizing
The
field-sizing
property enables you to control the sizing behavior of form inputs (i.e., they are given a default preferred size by default.) This property enables you to override the default behavior, allowing form controls to adjust in size to fit their contents.
This property is typically used to create form fields that shrinkwrap their content and grow as more text is entered. This works with input types that accept direct text input (for example,
text
and
url
), input type
file
, and
The first example is inaccessible: no relationship exists between the prompt and the
element.
In addition to an accessible name, the label provides a larger 'hit' area for mouse and touch screen users to click on or touch. By pairing a
with an
, clicking on either one will focus the
. If you use plain text to "label" your input, this won't happen. Having the prompt part of the activation area for the input is helpful for people with motor control conditions.
As web developers, it's important that we never assume that people will know all the things that we know. The diversity of people using the web—and by extension your website—practically guarantees that some of your site's visitors will have some variation in thought processes and/or circumstances that leads them to interpret your forms very differently from you without clear and properly-presented labels.
Placeholders are not accessible
The
placeholder
attribute lets you specify text that appears within the
element's content area itself when it is empty. The placeholder should never be required to understand your forms. It is not a label, and should not be used as a substitute, because it isn't. The placeholder is used to provide a hint as to what an inputted value should look like, not an explanation or prompt.
Not only is the placeholder not accessible to screen readers, but once the user enters any text into the form control, or if the form control already has a value, the placeholder disappears. Browsers with automatic page translation features may skip over attributes when translating, meaning the
placeholder
may not get translated.
Note:
Don't use the
placeholder
attribute if you can avoid it. If you need to label an
element, use the
element.
Client-side validation
Warning:
Client-side validation is useful, but it does
not
guarantee that the server will receive valid data. If the data must be in a specific format,
always
verify it also on the server-side, and return a
400
HTTP response
if the format is invalid.
In addition to using CSS to style inputs based on the
:valid
or
:invalid
UI states based on the current state of each input, as noted in the
UI pseudo-classes
section above, the browser provides for client-side validation on (attempted) form submission. On form submission, if there is a form control that fails constraint validation, supporting browsers will display an error message on the first invalid form control; displaying a default message based on the error type, or a message set by you.
Some input types and other attributes place limits on what values are valid for a given input. For example,
means only the number 2, 4, 6, 8, or 10 are valid. Several errors could occur, including a
rangeUnderflow
error if the value is less than 2,
rangeOverflow
if greater than 10,
stepMismatch
if the value is a number between 2 and 10, but not an even integer (does not match the requirements of the
step
attribute), or
typeMismatch
if the value is not a number.
For the input types whose domain of possible values is periodic (that is, at the highest possible value, the values wrap back around to the beginning rather than ending), it's possible for the values of the
max
and
min
properties to be reversed, which indicates that the range of permitted values starts at
min
, wraps around to the lowest possible value, then continues on until
max
is reached. This is particularly useful for dates and times, such as when you want to allow the range to be from 8 PM to 8 AM:
html
Specific attributes and their values can lead to a specific error
ValidityState
Validity object errors depend on the
attributes and their values:
Attribute
Relevant property
Description
max
validityState.rangeOverflow
Occurs when the value is greater than the maximum value as defined by
the
max
attribute
maxlength
validityState.tooLong
Occurs when the number of characters is greater than the number allowed by the
maxlength
property
min
validityState.rangeUnderflow
Occurs when the value is less than the minimum value as defined by the
min
attribute
minlength
validityState.tooShort
Occurs when the number of characters is less than the number required by the
minlength
property
pattern
validityState.patternMismatch
Occurs when a pattern attribute is included with a valid regular expression and the
value
does not match it.
required
validityState.valueMissing
Occurs when the
required
attribute is present but the value is
null
or radio or checkbox is not checked.
step
validityState.stepMismatch
The value doesn't match the step increment. Increment default is
, so only integers are valid on
type="number"
is step is not included.
step="any"
will never throw this error.
type
validityState.typeMismatch
Occurs when the value is not of the correct type, for example an email does not contain an
or a url doesn't contain a protocol.
If a form control doesn't have the
required
attribute, no value, or an empty string, is not invalid. Even if the above attributes are present, with the exception of
required
, an empty string will not lead to an error.
We can set limits on what values we accept, and supporting browsers will natively validate these form values and alert the user if there is a mistake when the form is submitted.
In addition to the errors described in the table above, the
validityState
interface contains the
badInput
valid
, and
customError
boolean readonly properties. The validity object includes:
validityState.valueMissing
validityState.typeMismatch
validityState.patternMismatch
validityState.tooLong
validityState.tooShort
validityState.rangeUnderflow
validityState.rangeOverflow
validityState.stepMismatch
validityState.badInput
validityState.valid
validityState.customError
For each of these Boolean properties, a value of
true
indicates that the specified reason validation may have failed is true, with the exception of the
valid
property, which is
true
if the element's value obeys all constraints.
If there is an error, supporting browsers will both alert the user and prevent the form from being submitted. A word of caution: if a custom error is set to a truthy value (anything other than the empty string or
null
), the form will be prevented from being submitted. If there is no custom error message, and none of the other properties return true,
valid
will be true, and the form can be submitted.
js
function validate(input) {
let validityState = input.validity;
if (validityState.valueMissing) {
input.setCustomValidity("A value is required");
} else if (validityState.rangeUnderflow) {
input.setCustomValidity("Your value is too low");
} else if (validityState.rangeOverflow) {
input.setCustomValidity("Your value is too high");
} else {
input.setCustomValidity("");
The last line, setting the custom validity message to the empty string is vital. If the user makes an error, and the validity is set, it will fail to submit, even if all the values are valid, until the message is
null
Custom validation error example
If you want to present a custom error message when a field fails to validate, you need to use the
Constraint Validation API
available on
(and related) elements. Take the following form:
html
The basic HTML form validation features will cause this to produce a default error message if you try to submit the form with either no valid filled in, or a value that does not match the
pattern
If you wanted to instead display custom error messages, you could use JavaScript like the following:
js
const nameInput = document.querySelector("input");
nameInput.addEventListener("input", () => {
nameInput.setCustomValidity("");
nameInput.checkValidity();
});
nameInput.addEventListener("invalid", () => {
if (nameInput.value === "") {
nameInput.setCustomValidity("Enter your username!");
} else {
nameInput.setCustomValidity(
"Usernames can only contain upper and lowercase letters. Try again!",
);
});
The example renders like so:
In brief:
We check the valid state of the input element every time its value is changed by running the
checkValidity()
method via the
input
event handler.
If the value is invalid, an
invalid
event is raised, and the
invalid
event handler function is run. Inside this function we work out whether the value is invalid because it is empty, or because it doesn't match the pattern, using an
if ()
block, and set a custom validity error message.
As a result, if the input value is invalid when the submit button is pressed, one of the custom error messages will be shown.
If it is valid, it will submit as you'd expect. For this to happen, the custom validity has to be cancelled, by invoking
setCustomValidity()
with an empty string value. We therefore do this every time the
input
event is raised. If you don't do this, and a custom validity was previously set, the input will register as invalid, even if it currently contains a valid value on submission.
Note:
Always validate input constraints both client side and server side. Constraint validation doesn't remove the need for validation on the
server side
. Invalid values can still be sent by older browsers or by bad actors.
Note:
Firefox supported a proprietary error attribute —
x-moz-errormessage
— for many versions, which allowed you set custom error messages in a similar way. This has been removed as of version 66 (see
Firefox bug 1513890
).
Localization
The allowed inputs for certain
types depend on the locale. In some locales, 1,000.00 is a valid number, while in other locales the valid way to enter this number is 1.000,00.
Firefox uses the following heuristics to determine the locale to validate the user's input (at least for
type="number"
):
Try the language specified by a
lang
xml:lang
attribute on the element or any of its parents.
Try the language specified by any
Content-Language
HTTP header. Or,
If none specified, use the browser's locale.
Labels
When including inputs, it is an accessibility requirement to add labels alongside. This is needed so those who use assistive technologies can tell what the input is for. Also, clicking or touching a label gives focus to the label's associated form control. This improves the accessibility and usability for sighted users, increases the area a user can click or touch to activate the form control. This is especially useful (and even needed) for radio buttons and checkboxes, which are tiny. For more information about labels in general see
Labels
The following is an example of how to associate the
with an
element in the above style. You need to give the
an
id
attribute. The
then needs a
for
attribute whose value is the same as the input's
id
html
Size
Interactive elements such as form input should provide an area large enough that it is easy to activate them. This helps a variety of people, including people with motor control issues and people using non-precise forms of input such as a stylus or fingers. A minimum interactive size of 44×44
CSS pixels
is recommended.
Understanding Success Criterion 2.5.5: Target Size | W3C Understanding WCAG 2.1
Target Size and 2.5.5 | Adrian Roselli
Quick test: Large touch targets - The A11Y Project
Technical summary
Content categories
Flow content
, listed, submittable, resettable, form-associated element,
phrasing content
. If the
type
is not
hidden
, then labelable element, palpable content.
Permitted content
None; it is a
void element
Tag omission
Must have a start tag and must not have an end tag.
Permitted parents
Any element that accepts
phrasing content
Implicit ARIA role
type=button
button
type=checkbox
checkbox
type=email
with no
list
attribute:
textbox
with
list
attribute:
combobox
type=image
button
type=number
spinbutton
type=radio
radio
type=range
slider
type=reset
button
type=search
with no
list
attribute:
searchbox
with
list
attribute:
combobox
type=submit
button
type=tel
with no
list
attribute:
textbox
with
list
attribute:
combobox
type=text
with no
list
attribute:
textbox
with
list
attribute:
combobox
type=url
with no
list
attribute:
textbox
with
list
attribute:
combobox
type=color|date|datetime-local|file|hidden|month|password|time|week
no corresponding role
Permitted ARIA roles
type=button
checkbox
combobox
link
menuitem
menuitemcheckbox
menuitemradio
option
radio
switch
tab
type=checkbox
button
when used
with
aria-pressed
menuitemcheckbox
option
switch
type=image
link
menuitem
menuitemcheckbox
menuitemradio
radio
switch
type=radio
menuitemradio
type=text
with no
list
attribute:
combobox
searchbox
spinbutton
type=color|date|datetime-local|email|file|hidden|
month|number|password|range|reset|search|submit|tel|url|week
or
text
with
list
attribute: no
role
permitted
DOM interface
HTMLInputElement
Specifications
Specification
HTML
# the-input-element
Browser compatibility
See also
CSS
appearance
property
Your first HTML form
How to structure an HTML form
The native form widgets
Sending form data
Form constraint validation
Styling HTML forms
Help improve MDN
Learn how to contribute
This page was last modified on
Feb 13, 2026
by
MDN contributors
View this page on GitHub
Report a problem with this content