<input>:输入(表单输入)元素

<input> HTML 元素用于为基于 Web 的表单创建交互式控件,以便接受来自用户的数据;根据设备和 user agent,可以使用多种类型的输入数据和控制小部件。由于输入类型和属性的组合数量众多,<input> 元素是所有 HTML 中最强大和最复杂的元素之一。

¥The <input> 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 <input> 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

<输入>类型

¥\ types

<input> 的工作方式根据其 type 属性的值而有很大差异,因此不同的类型在其自己单独的参考页中进行了介绍。如果不指定该属性,则默认采用 text 类型。

¥How an <input> 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:

类型 描述 基本示例
button 没有默认行为的按钮,显示 value 属性的值,默认为空。
  </td>
</tr>
<tr>
  <td>checkbox</td>
  <td>允许选择/取消选择单个值的复选框。</td> 
  <td id="examplecheckbox">
    <pre class="brush: html hidden">

<input type="checkbox" name="checkbox"/>

  </td>
</tr> 
<tr>
  <td>color</td>
  <td>
    用于指定颜色的控件;在支持浏览器中处于活动状态时打开颜色选择器。
  </td> 
  <td id="examplecolor">
    <pre class="brush: html hidden">

<input type="color" name="color"/>

  </td>
</tr>
<tr>
  <td>date</td>
  <td>
    用于输入日期(年、月、日,没有时间)的控件。当在支持浏览器中处于活动状态时,打开日期选择器或年、月、日的数字轮。
  </td> 
  <td id="exampledate">
    <pre class="brush: html hidden">

<input type="date" name="date"/>

  </td>
</tr> 
<tr>
  <td>
    datetime-local
  </td>
  <td>
    用于输入日期和时间的控件,不带时区。当在支持浏览器中处于活动状态时,打开日期选择器或日期和时间组件的数字轮。
  </td> 
  <td id="exampledtl">
    <pre class="brush: html hidden">

<input type="datetime-local" name="datetime-local"/>

  </td>
</tr>
<tr>
  <td>email</td>
  <td>
    用于编辑电子邮件地址的字段。看起来像 
    <code>text</code> 输入,但具有验证参数和相关键盘,支持具有动态键盘的浏览器和设备。
  </td> 
  <td id="exampleemail">
    <pre class="brush: html hidden">

<input type="email" name="email"/>

  </td>
</tr> 
<tr>
  <td>file</td>
  <td>
    允许用户选择文件的控件。使用  <a href="#accept"><code>accept</code></a> 属性定义控件可以选择的文件类型。
  </td> 
  <td id="examplefile">
    <pre class="brush: html hidden">

<input type="file" accept="image/, text/" name="file"/>

  </td>
</tr>
<tr>
  <td>hidden</td>
  <td>
    不显示但其值提交到服务器的控件。下一栏中有一个示例,但它被隐藏了!
  </td> 
  <td id="examplehidden">
    <pre class="brush: html hidden">

<input id="userId" name="userId" type="hidden" value="abc123">

  </td>
</tr> 
<tr>
  <td>image</td>
  <td>
    图形  <code>submit</code> 按钮。显示由  <code>src</code> 属性定义的图片。如果图片  <a href="#src"><code>src</code></a> 丢失,则显示  <a href="#alt"><code>alt</code></a> 属性。
  </td> 
  <td id="exampleimage">
    <pre class="brush: html hidden">

<input type="image" name="image" src="" alt="image input"/>

  </td>
</tr>
<tr>
  <td>month</td>
  <td>用于输入月份和年份的控件,不带时区。</td> 
  <td id="examplemonth">
    <pre class="brush: html hidden">

<input type="month" name="month"/>

  </td>
</tr> 
<tr>
  <td>number</td>
  <td>
    用于输入数字的控件。显示加载控件并添加默认验证。在某些具有动态键盘的设备中显示数字键盘。
  </td> 
  <td id="examplenumber">
    <pre class="brush: html hidden">

<input type="number" name="number"/>

  </td>
</tr> 
<tr>
  <td>password</td>
  <td>
    其值被隐藏的单行文本字段。如果网站不安全,将提醒用户。
  </td> 
  <td id="examplepassword">
    <pre class="brush: html hidden">

<input type="password" name="password"/>

  </td>
</tr> 
<tr>
  <td>radio</td>
  <td>
    一个单选按钮,允许从具有相同  <a href="#name"><code>name</code></a> 值的多个选项中选择单个值。
  </td> 
  <td id="exampleradio">
    <pre class="brush: html hidden">

<input type="radio" name="radio"/>

  </td>
</tr> 
<tr>
  <td>range</td>
  <td>
    用于输入数字的控件,其确切值并不重要。显示为默认为中间值的范围小部件。与  <a href="#min"><code>min</code></a> 和  <a href="#max"><code>max</code></a> 结合使用来定义可接受值的范围。
  </td> 
  <td id="examplerange">
    <pre class="brush: html hidden">

<input type="range" name="range" min="0" max="25"/>

  </td>
</tr> 
<tr>
  <td>reset</td>
  <td>
    将表单内容重置为默认值的按钮。不建议。
  </td> 
  <td id="examplereset">
    <pre class="brush: html hidden">

<input type="reset" name="reset"/>

  </td>
</tr> 
<tr>
  <td>search</td>
  <td>
    用于输入搜索字符串的单行文本字段。换行符会自动从输入值中删除。支持浏览器中可能包含一个可用于清除字段的删除图标。在某些带有动态键盘的设备上显示搜索图标而不是输入键。
  </td> 
  <td id="examplesearch">
    <pre class="brush: html hidden">

<input type="search" name="search"/>

  </td>
</tr> 
<tr>
  <td>submit</td>
  <td>提交表单的按钮。</td> 
  <td id="examplesubmit">
    <pre class="brush: html hidden">

<input type="submit" name="submit"/>

  </td>
</tr> 
<tr>
  <td>tel</td>
  <td>
    用于输入调用号码的控件。在某些具有动态键盘的设备中显示调用键盘。
  </td> 
  <td id="exampletel">
    <pre class="brush: html hidden">

<input type="tel" name="tel"/>

  </td>
</tr> 
<tr>
  <td>text</td>
  <td>
    默认值。单行文本字段。换行符会自动从输入值中删除。
  </td> 
  <td id="exampletext">
    <pre class="brush: html hidden">

<input type="text" name="text"/>

  </td>
</tr> 
<tr>
  <td>time</td>
  <td>用于输入不带时区的时间值的控件。</td> 
  <td id="exampletime">
    <pre class="brush: html hidden">

<input type="time" name="time"/>

  </td>
</tr> 
<tr>
  <td>url</td>
  <td>
    用于输入 URL 的字段。看起来像  <code>text</code> 输入,但具有验证参数和相关键盘,支持具有动态键盘的浏览器和设备。
  </td> 
  <td id="exampleurl">
    <pre class="brush: html hidden">

<input type="url" name="url"/>

  </td>
</tr> 
<tr>
  <td>week</td>
  <td>
    用于输入日期的控件,该日期由周年数字和不带时区的周数字组成。
  </td> 
  <td id="exampleweek">
    <pre class="brush: html hidden">

<input type="week" name="week"/>

  </td>
</tr> 
<tr>
  <th colspan="3">过时的值</th>
</tr> 
<tr>
  <td><code>datetime</code> 
  Deprecated
</td>
  <td>
    用于输入基于 UTC 时区的日期和时间(小时、分钟、秒和秒的小数部分)的控件。
  </td> 
  <td id="exampledatetime">
    <pre class="brush: html hidden">

<input type="datetime" name="datetime"/>

  </td>
</tr>

属性

¥Attributes

<input> 元素之所以如此强大,是因为它的属性;上面示例中描述的 type 属性是最重要的。由于每个 <input> 元素,无论类型如何,都基于 HTMLInputElement 接口,因此它们在技术上共享完全相同的属性集。然而,实际上,大多数属性仅对输入类型的特定子集产生影响。此外,某些属性影响输入的方式取决于输入类型,以不同的方式影响不同的输入类型。

¥The <input> element is so powerful because of its attributes; the type attribute, described with examples above, being the most important. Since every <input> 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.

<input> 元素的属性包括 全局 HTML 属性,此外还包括:

¥Attributes for the <input> element include the global HTML attributes and additionally:

属性 类型或类型 描述
accept file 文件上传控件中预期文件类型的提示
alt image 图片类型的 alt 属性。需要可访问性
autocapitalize urlemailpassword 之外的所有 控制输入文本中的自动大写。
autocomplete checkboxradio 和按钮之外的所有内容 表单自动填充功能的提示
capture file 文件上传控件中的媒体捕获输入法
checked checkboxradio 是否检查命令或控制
dirname hidden, text, search, url, tel, email 用于在表单提交中发送元素方向性的表单字段名称
disabled all 表单控件是否禁用
form all 将控件与表单元素关联
formaction imagesubmit 用于表单提交的 URL
formenctype imagesubmit 用于表单提交的表单数据集编码类型
formmethod imagesubmit 用于表单提交的 HTTP 方法
formnovalidate imagesubmit 绕过表单控件验证以提交表单
formtarget imagesubmit 表单提交的浏览上下文
height image <img> 的高度属性相同;垂直尺寸
list hiddenpasswordcheckboxradio 和按钮之外的所有内容 自动补齐选项 <datalist> 的 id 属性的值
max date, month, week, time, datetime-local, number, range 最大值
maxlength text, search, url, tel, email, password value 的最大长度(字符数)
min date, month, week, time, datetime-local, number, range 最小值
minlength text, search, url, tel, email, password value 的最小长度(字符数)
multiple emailfile 布尔值。是否允许多个值
name all 表单控件的名称。作为名称/值对的一部分与表单一起提交
pattern text, search, url, tel, email, password value 必须匹配的模式才有效
placeholder text, search, url, tel, email, password, number 未设置值时出现在表单控件中的文本
popovertarget button 指定 <input type="button"> 作为弹出框元素的控件
popovertargetaction button 指定弹出框控件应执行的操作
readonly hiddenrangecolorcheckboxradio 和按钮之外的所有按钮 布尔值。该值不可编辑
required hiddenrangecolor 和按钮之外的所有内容 布尔值。需要提供一个值或必须检查该值才能提交表单
size text, search, url, tel, email, password 控件的大小
src image <img>src 属性相同;图片资源地址
step date, month, week, time, datetime-local, number, range 有效的增量值
type all 表单控件类型
value image 外的所有 控件的初始值
width image <img>width 属性相同

标准属性的描述后面列出了一些附加的非标准属性。

¥A few additional non-standard attributes are listed following the descriptions of the standard attributes.

个人属性

¥Individual attributes

accept

仅对 file 输入类型有效,accept 属性定义在 file 上传控件中可选择哪些文件类型。请参阅 file 输入类型。

alt

仅对 image 按钮有效,alt 属性为图片提供替代文本,如果图片 src 丢失或无法加载,则显示该属性的值。请参阅 image 输入类型。

autocapitalize

控制输入的文本是否自动大写,如果是,则以何种方式自动大写。有关详细信息,请参阅 autocapitalize 全局属性页面。

autocomplete

(不是布尔属性!)autocomplete 属性采用空格分隔的字符串作为其值,该字符串描述输入应提供的自动补齐功能类型(如果有)。自动补齐的典型实现会调用先前在同一输入字段中输入的值,但也可以存在更复杂形式的自动补齐。例如,浏览器可以与设备的联系人列表集成,以在电子邮件输入字段中自动补齐 email 地址。请参阅 autocomplete 了解允许的值。

autocomplete 属性在 hiddentextsearchurltelemaildatemonthweektimedatetime-localnumberrangecolorpassword 上有效。此属性对不返回数字或文本数据的输入类型没有影响,对除 checkboxradiofile 或任何按钮类型之外的所有输入类型均有效。

请参阅 autocomplete 属性 了解更多信息,包括有关密码安全性的信息以及 autocomplete 对于 hidden 与其他输入类型有何细微不同。

autofocus

一个布尔属性,如果存在,则指示当页面完成加载时(或当包含元素的 <dialog> 已显示时),输入应自动获得焦点。

注意:具有 autofocus 属性的元素可能会在 DOMContentLoaded 事件触发之前获得焦点。

¥Note: An element with the autofocus attribute may gain focus before the DOMContentLoaded event is fired.

文档中不得有多个元素具有 autofocus 属性。如果放置在多个元素上,则第一个具有该属性的元素将获得焦点。

autofocus 属性不能用于 hidden 类型的输入,因为无法聚焦隐藏输入。

警告:自动聚焦表单控件可能会让使用屏幕阅读技术的视障人士和有认知障碍的人士感到困惑。当分配 autofocus 时,屏幕阅读器会将用户 "teleport" 引导至表单控件,而不会事先警告他们。

¥Warning: Automatically focusing a form control can confuse visually-impaired people using screen-reading technology and people with cognitive impairments. When autofocus is assigned, screen-readers "teleport" their user to the form control without warning them beforehand.

应用 autofocus 属性时,请仔细考虑可访问性。自动聚焦于控件可能会导致页面在加载时滚动。焦点还可能导致动态键盘在某些触摸设备上显示。虽然屏幕阅读器将读出接收焦点的表单控件的标签,但屏幕阅读器不会读出标签之前的任何内容,并且小型设备上有视力的用户同样会遗漏由前面的内容创建的上下文。

capture

capture 属性在 HTML 媒体捕获规范中引入,仅对 file 输入类型有效,它定义应使用哪种媒体(麦克风、视频或摄像头)来捕获新文件,以便在支持场景中使用 file 上传控件进行上传。请参阅 file 输入类型。

checked

radiocheckbox 类型均有效,checked 是布尔属性。如果存在于 radio 类型上,则表示单选按钮是同名单选按钮组中当前选定的单选按钮。如果出现在 checkbox 类型上,则表示默认情况下选中该复选框(在页面加载时)。它并不指示当前是否选中此复选框:如果复选框的状态发生更改,则此内容属性不会反映更改。(仅更新了 HTMLInputElementchecked IDL 属性。)

注意:与其他输入控件不同,复选框和单选按钮值仅在当前为 checked 时才包含在提交的数据中。如果是,则提交已检查控件的名称和值。

¥Note: Unlike other input controls, a checkboxes and radio buttons value are only included in the submitted data if they are currently checked. If they are, the name and the value(s) of the checked controls are submitted.

例如,如果 namefruit 的复选框的 valuecherry,并且该复选框被选中,则提交的表单数据将包括 fruit=cherry。如果该复选框未激活,则它根本不会在表单数据中列出。复选框和单选按钮的默认 valueon

¥For example, if a checkbox whose name is fruit has a value of cherry, and the checkbox is checked, the form data submitted will include fruit=cherry. If the checkbox isn't active, it isn't listed in the form data at all. The default value for checkboxes and radio buttons is on.

dirname

dirname 属性对 hiddentextsearchurltelemail 输入类型有效,可以提交元素的方向性。包含后,表单控件将提交两个名称/值对:第一个是 namevalue,第二个是 dirname 属性的值作为名称,其值为 ltrrtl 由浏览器设置。

html
<form action="page.html" method="post">
  <label>
    Fruit:
    <input type="text" name="fruit" dirname="fruit-dir" value="cherry" />
  </label>
  <input type="submit" />
</form>
<!-- page.html?fruit=cherry&fruit-dir=ltr -->

当提交上面的表单时,输入会导致发送 fruit=cherryname / value 对和 fruit-dir=ltrdirname / 方向对。有关详细信息,请参阅 dirname 属性

disabled

布尔属性,如果存在,则指示用户不应与输入交互。禁用的输入通常用较暗的颜色呈现,或者使用某种其他形式的指示来指示该字段不可用。

具体来说,禁用的输入不会收到 click 事件,并且禁用的输入不会随表单一起提交。

注意:尽管规范没有要求,Firefox 默认情况下会跨页面加载 保持动态禁用状态<input>。使用 autocomplete 属性来控制此功能。

¥Note: Although not required by the specification, Firefox will by default persist the dynamic disabled state of an <input> across page loads. Use the autocomplete attribute to control this feature.

form

指定与输入关联的 <form> 元素(即其表单所有者)的字符串。该字符串的值(如果存在)必须与同一文档中 <form> 元素的 id 匹配。如果未指定此属性,则 <input> 元素与最近的包含表单(如果有)相关联。

form 属性允许你将输入放置在文档中的任何位置,但将其包含在文档中其他位置的表单中。

注意:一个输入只能与一个表单关联。

¥Note: An input can only be associated with one form.

formaction

仅对 imagesubmit 输入类型有效。有关详细信息,请参阅 submit 输入类型。

formenctype

仅对 imagesubmit 输入类型有效。有关详细信息,请参阅 submit 输入类型。

formmethod

仅对 imagesubmit 输入类型有效。有关详细信息,请参阅 submit 输入类型。

formnovalidate

仅对 imagesubmit 输入类型有效。有关详细信息,请参阅 submit 输入类型。

formtarget

仅对 imagesubmit 输入类型有效。有关详细信息,请参阅 submit 输入类型。

height

仅对 image 输入按钮有效,height 是要显示的图片文件的高度,以代表图形提交按钮。请参阅 image 输入类型。

id

全局属性对所有元素有效,包括所有输入类型,它定义了一个唯一标识符(ID),该标识符在整个文档中必须是唯一的。其目的是在链接时识别元素。该值用作 <label>for 属性的值,以将标签与表单控件链接起来。参见 <label>

inputmode

全局值对所有元素都有效,它向浏览器提供有关编辑此元素或其内容时要使用的虚拟键盘配置类型的提示。值包括 nonetexttelurlemailnumericdecimalsearch

list

赋予 list 属性的值应该是位于同一文档中的 <datalist> 元素的 id<datalist> 提供了一个预定义值列表来建议用户进行此输入。列表中与 type 不兼容的任何值都不包含在建议选项中。提供的值是建议,而不是要求:用户可以从此预定义列表中进行选择或提供不同的值。

适用于 textsearchurltelemaildatemonthweektimedatetime-localnumberrangecolor

根据规范,hiddenpasswordcheckboxradiofile 或任何按钮类型不支持 list 属性。

根据浏览器的不同,用户可能会看到建议的自定义调色板、范围内的刻度线,甚至是像 <select> 一样打开但允许使用未列出的值的输入。查看 浏览器兼容性表 的其他输入类型。

请参阅 <datalist> 元素。

max

datemonthweektimedatetime-localnumberrange 有效,它定义了允许值范围内的最大值。如果输入到元素中的 value 超过此值,则该元素将失败 约束验证。如果 max 属性的值不是数字,则该元素没有最大值。

有一种特殊情况:如果数据类型是周期性的(例如日期或时间),则 max 的值可能低于 min 的值,这表明范围可能会回绕;例如,这允许你指定从晚上 10 点到凌晨 4 点的时间范围。

maxlength

textsearchurltelemailpassword 有效,它定义用户可以在字段中输入的最大字符串长度(以 UTF-16 代码单元测量)。这必须是 0 或更大的整数值。如果未指定 maxlength,或者指定了无效值,则该字段没有最大长度。该值还必须大于或等于 minlength 的值。

如果输入字段的文本长度大于 maxlength UTF-16 代码单元长度,则输入将失败 约束验证。默认情况下,浏览器会阻止用户输入超过 maxlength 属性允许的字符。请参阅 客户端验证 了解更多信息。

min

datemonthweektimedatetime-localnumberrange 有效,它定义允许值范围内的最大负值。如果输入到元素中的 value 小于此值,则该元素失败 约束验证。如果 min 属性的值不是数字,则该元素没有最小值。

该值必须小于或等于 max 属性的值。如果 min 属性存在但未指定或无效,则不应用 min 值。如果 min 属性有效且非空值小于 min 属性允许的最小值,则约束验证将阻止表单提交。请参阅 客户端验证 了解更多信息。

有一种特殊情况:如果数据类型是周期性的(例如日期或时间),则 max 的值可能低于 min 的值,这表明范围可能会回绕;例如,这允许你指定从晚上 10 点到凌晨 4 点的时间范围。

minlength

textsearchurltelemailpassword 有效,它定义用户可以在输入字段中输入的最小字符串长度(以 UTF-16 代码单元测量)。该值必须是小于或等于 maxlength 指定值的非负整数值。如果未指定 minlength,或指定了无效值,则输入没有最小长度。

如果输入字段的文本长度小于 minlength UTF-16 代码单元长度,则输入将失败 约束验证,从而阻止表单提交。请参阅 客户端验证 了解更多信息。

multiple

布尔 multiple 属性(如果设置)意味着用户可以在电子邮件小部件中输入逗号分隔的电子邮件地址,或者可以使用 file 输入选择多个文件。请参阅 emailfile 输入类型。

name

指定输入控件名称的字符串。当提交表单数据时,该名称与控件的值一起提交。

name 视为必需属性(即使不是)。如果输入未指定 name,或 name 为空,则输入的值不会随表单一起提交!(禁用的控件、未选中的单选按钮、未选中的复选框和重置按钮也不会发送。)

有两种特殊情况:

  1. _charset_ :如果用作 hidden 类型的 <input> 元素的名称,则输入的 value 会由 user agent 自动设置为用于提交表单的字符编码。
  2. isindex:由于历史原因,isindex 这个名字是不被允许的。

name 属性为单选按钮创建了独特的行为。

一次只能选中一组同名单选按钮中的一个单选按钮。选择该组中的任何单选按钮都会自动取消选择同一组中当前选定的任何单选按钮。如果提交表单,则选中的单选按钮的值将与名称一起发送,

当按 Tab 键进入一系列同名单选按钮组时,如果选中其中一个,则该按钮将获得焦点。如果它们没有按源顺序分组在一起,如果选中了其中一个组,则在遇到组中的第一个组时开始按 Tab 键进入该组,并跳过所有未选中的组。换句话说,如果选中一个单选按钮,则 Tab 键切换会跳过组中未选中的单选按钮。如果未选中任何一项,则当到达同名组中的第一个按钮时,单选按钮组将获得焦点。

一旦组中的一个单选按钮获得焦点,使用箭头键将导航到所有同名的单选按钮,即使这些单选按钮没有按源顺序分组在一起。

当输入元素被赋予 name 时,该名称将成为所属表单元素的 HTMLFormElement.elements 属性的属性。如果你有一个输入的 name 设置为 guest,另一个输入的 name 设置为 hat-size,则可以使用以下代码:

js
let form = document.querySelector("form");

let guestName = form.elements.guest;
let hatSize = form.elements["hat-size"];

当此代码运行时,guestName 将是 guest 字段的 HTMLInputElementhatSize 将是 hat-size 字段的对象。

警告:避免为表单元素提供与表单的内置属性相对应的 name,因为随后你将使用对相应输入的引用来覆盖预定义的属性或方法。

¥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

pattern 属性对 textsearchurltelemailpassword 有效,它定义一个正则表达式,输入的 value 必须与该正则表达式匹配,以便值能够传递 约束验证。它必须是有效的 JavaScript 正则表达式,如 RegExp 类型所使用的,以及我们的 正则表达式指南 中记录的;编译正则表达式时指定 'u' 标志,以便将模式视为 Unicode 代码点序列,而不是 ASCII。模式文本周围不应指定正斜杠。

如果 pattern 属性存在但未指定或无效,则不应用正则表达式,并且完全忽略该属性。如果模式属性有效并且非空值与模式不匹配,则约束验证将阻止表单提交。

注意:如果使用 pattern 属性,请通过在附近添加解释性文本来告知用户预期的格式。你还可以包含 title 属性来解释匹配模式的要求;大多数浏览器都会将此标题显示为工具提示。为了可访问性,需要可见的解释。工具提示是一项增强功能。

¥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.

请参阅 客户端验证 了解更多信息。

placeholder

placeholder 属性对 textsearchurltelemailpasswordnumber 有效,向用户提供有关该字段中期望的信息类型的简短提示。它应该是一个单词或短语,提供有关预期数据类型的提示,而不是解释或提示。文本不得包含回车或换行。例如,如果一个字段需要捕获用户的名字,并且其标签是 "名",那么合适的占位符可能是 "例如 穆斯塔法"。

注意:placeholder 属性在语义上不如解释表单的其他方法那么有用,并且可能会导致内容出现意外的技术问题。请参阅 标签 了解更多信息。

¥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

<input type="button"> 元素变成弹出框控制按钮;将要控制的弹出框元素的 ID 作为其值。有关更多详细信息,请参阅 Popover API 登陆页面。

popovertargetaction

指定要对由控件 <input type="button"> 控制的弹出框元素执行的操作。可能的值为:

"hide"

该按钮将隐藏显示的弹出窗口。如果你尝试隐藏已经隐藏的弹出窗口,则不会采取任何操作。

"show"

该按钮将显示一个隐藏的弹出窗口。如果你尝试显示已显示的弹出窗口,则不会采取任何操作。

"toggle"

该按钮将在显示和隐藏之间切换弹出窗口。如果弹出窗口隐藏,则会显示;如果弹出窗口显示,它将被隐藏。如果省略 popovertargetaction,则 "toggle" 是将由控制按钮执行的默认操作。

readonly

布尔属性,如果存在,则指示用户不应能够编辑输入的值。textsearchurltelemaildatemonthweektimedatetime-localnumberpassword 输入类型支持 readonly 属性。

请参阅 HTML 属性:readonly 了解更多信息。

required

required 是一个布尔属性,如果存在,则指示用户必须在提交所属表单之前指定输入值。textsearchurltelemaildatemonthweektimedatetime-localnumberpasswordcheckboxradiofile 输入支持 required 属性。

有关详细信息,请参阅 客户端验证HTML 属性:required

size

emailpasswordtelurltext 有效,size 属性指定显示多少输入。基本上创建与设置 CSS width 属性相同的结果,但有一些特殊之处。值的实际单位取决于输入类型。对于 passwordtext,它是字符数(或 em 单位),默认值为 20,对于其他,它是像素(或 px 单位)。CSS width 优先于 size 属性。

src

仅对 image 输入按钮有效,src 是字符串,指定要显示的图片文件的 URL,以表示图形提交按钮。请参阅 image 输入类型。

step

datemonthweektimedatetime-localnumberrange 有效,step 属性是一个数字,指定值必须遵循的粒度。

如果没有明确包含:

  • 对于 numberrangestep 默认为 1。
  • 每个日期/时间输入类型都有一个适合该类型的默认 step 值;查看各个输入页面:datedatetime-localmonthtimeweek

该值必须是正数(整数或浮点数)或特殊值 any,这意味着不暗示任何步进,并且允许任何值(除非其他约束,例如 minmax)。

如果未显式设置 any,则 number、日期/时间输入类型和 range 输入类型的有效值等于步进的基础 — min 值和步进值的增量,直至 max 值(如果指定)。

例如,如果你有 <input type="number" min="10" step="2">,则任何偶数(10 或更大)都是有效的。如果省略,<input type="number">、任何整数都有效,但浮点数(如 4.2)无效,因为 step 默认为 1。为了使 4.2 有效,step 必须设置为 any、0.1、0.2,或者任何 min 值必须是以 .2 结尾的数字,例如 <input type="number" min="-5.2">

注意:当用户输入的数据不符合步进配置时,该值在约束验证中被视为无效,并将与 :invalid 伪类匹配。

¥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.

请参阅 客户端验证 了解更多信息。

tabindex

全局属性对所有元素有效,包括所有输入类型,一个整数属性,指示元素是否可以获取输入焦点(可聚焦),是否应该参与顺序键盘导航。由于除隐藏类型输入之外的所有输入类型都是可聚焦的,因此不应在表单控件上使用此属性,因为这样做将需要管理文档中所有元素的焦点顺序,如果这样做,可能会损害可用性和可访问性 错误地。

title

全局属性对所有元素有效,包括所有输入类型,包含表示与其所属元素相关的咨询信息的文本。此类信息通常但不一定作为工具提示呈现给用户。标题不应用作表单控件用途的主要解释。相反,请使用 <label> 元素,并将 for 属性设置为表单控件的 id 属性。参见下面的 标签

type

指定要呈现的控件类型的字符串。例如,要创建复选框,请使用值 checkbox。如果省略(或指定未知值),则使用输入类型 text,创建纯文本输入字段。

允许的值列在上面的 输入类型 中。

value

输入控件的值。当在 HTML 中指定时,这是初始值,从那时起,可以随时使用 JavaScript 访问相应 HTMLInputElement 对象的 value 属性来更改或检索它。value 属性始终是可选的,但对于 checkboxradiohidden 应视为强制属性。

width

仅对 image 输入按钮有效,width 是要显示的代表图形提交按钮的图片文件的宽度。请参阅 image 输入类型。

非标准属性

¥Non-standard attributes

以下非标准属性在某些浏览器上也可用。一般来说,除非没有办法,否则应避免使用它们。

¥The following non-standard attributes are also available on some browsers. As a general rule, you should avoid using them unless it can't be helped.

属性 描述
autocorrect 指示自动更正是 on 还是 off 的字符串。仅限 Safari。
incremental 是否发送重复的 search 事件以允许在用户仍在编辑字段值时更新实时搜索结果。仅限 WebKit 和 Blink(Safari、Chrome、Opera 等)。
mozactionhint Deprecated

一个字符串,指示用户在编辑字段时按下 EnterReturn 键时将采取的操作类型;这用于确定虚拟键盘上该键的适当标签。由于此属性已弃用,请改用 enterkeyhint

orient 设置范围滑块的方向。仅限 Firefox
results 先前搜索查询的下拉列表中应显示的最大项目数。仅限 Safari。
webkitdirectory 一个布尔值,指示是否只允许用户选择一个目录(或多个目录,如果 multiple 也存在)
autocorrect Non-standard

(仅限 Safari)。一个字符串,指示用户编辑此字段时是否激活自动更正。允许的值为:

on

启用自动更正拼写错误,以及处理文本替换(如果配置了)。

off

禁用自动更正和文本替换。

incremental Non-standard

布尔属性 incremental 是一个 WebKit 和 Blink 扩展(因此受 Safari、Opera、Chrome 等支持),如果存在,它会告诉 user agent 将输入作为实时搜索进行处理。当用户编辑字段的值时,用户代理将 search 事件发送到表示搜索框的 HTMLInputElement 对象。这允许你的代码在用户编辑搜索时实时更新搜索结果。

如果未指定 incremental,则仅当用户显式启动搜索时(例如在编辑字段时按 EnterReturn 键)才会发送 search 事件。

search 事件是有速率限制的,因此它的发送频率不会超过实现定义的间隔。

orient Non-standard

与影响 <progress><meter> 元素的 -moz-orient 非标准 CSS 属性类似,orient 属性定义范围滑块的方向。值包括 horizontal(表示范围水平呈现)和 vertical(表示范围垂直呈现)。请参阅 创建垂直表单控件 了解创建垂直表单控件的现代方法。

results Non-standard

results 属性(仅 Safari 支持)是一个数值,可让你覆盖 <input> 元素原生提供的先前搜索查询下拉菜单中显示的最大条目数。

该值必须是非负十进制数。如果未提供或给出了无效值,则使用浏览器的默认最大条目数。

webkitdirectory Non-standard

布尔值 webkitdirectory 属性(如果存在)指示用户在文件选择器界面中只能选择目录。有关更多详细信息和示例,请参阅 HTMLInputElement.webkitdirectory

尽管最初仅针对基于 WebKit 的浏览器实现,但 webkitdirectory 也可在 Microsoft Edge 以及 Firefox 50 及更高版本中使用。然而,尽管它有相对广泛的支持,但它仍然不是标准,除非你别无选择,否则不应使用。

方法

¥Methods

HTMLInputElement 接口提供了以下方法,代表 DOM 中的 <input> 元素。还可以使用由父接口 HTMLElementElementNodeEventTarget 指定的那些方法。

¥The following methods are provided by the HTMLInputElement interface which represents <input> elements in the DOM. Also available are those methods specified by the parent interfaces, HTMLElement, Element, Node, and EventTarget.

checkValidity()

如果元素的值通过有效性检查,则返回 true;否则,返回 false 并在元素上触发 invalid 事件。

reportValidity()

如果元素的值通过有效性检查,则返回 true;否则,返回 false,在元素上触发 invalid 事件,并且(如果该事件未取消)向用户报告问题。

select()

如果 <input> 元素的内容可选择,则选择该元素的全部内容。对于没有可选文本内容的元素(例如可视颜色选择器或日历日期输入),此方法不执行任何操作。

setCustomValidity()

设置在输入元素的值无效时显示的自定义消息。

setRangeText()

将输入元素中指定字符范围的内容设置为给定字符串。selectMode 参数可用于控制现有内容的影响方式。

setSelectionRange()

选择文本输入元素中指定范围的字符。对于不作为文本输入字段呈现的输入不执行任何操作。

showPicker()

显示输入元素的浏览器选择器,通常在选择元素时显示,但通过按下按钮或其他用户交互触发。

stepDown()

默认情况下,将数字输入的值递减 1,或递减指定的单位数。

stepUp()

将数字输入的值增加 1 或指定的单位数。

CSS

输入作为替换元素,具有一些不适用于非表单元素的功能。有些 CSS 选择器可以根据 UI 功能专门针对表单控件,也称为 UI 伪类。输入元素也可以通过属性选择器的类型来定位。还有一些属性也特别有用。

¥Inputs, being replaced elements, have a few features not applicable to non form elements. There are CSS selectors that can specifically target form controls based on their UI features, also known as UI pseudo-classes. The input element can also be targeted by type with attribute selectors. There are some properties that are especially useful as well.

UI 伪类

¥UI pseudo-classes

Captions super relevant to the <input> element:
伪类 描述
:enabled 任何当前启用的元素可以被激活(选择、单击、键入等)或接受焦点,并且还具有禁用状态,在该状态下它无法被激活或接受焦点。
:disabled 任何当前禁用的元素具有启用状态,这意味着它可以被激活(选择、单击、键入等)或接受焦点(如果未禁用)。
:read-only 用户不可编辑元素
:read-write 用户可编辑的元素。
:placeholder-shown 当前显示 placeholder 文字 的元素,包括 <input><textarea> 元素,其中存在 placeholder 属性,但尚无任何值。
:default 一组相关元素中默认的表单元素。匹配在页面加载或渲染时检查的 checkboxradio 输入类型。
:checked 匹配当前选中的 checkboxradio 输入类型(以及当前选择的 <select> 中的 <option>)。
:indeterminate checkbox 元素的不确定属性被 JavaScript 设置为 true,radio 元素,当表单中具有相同名称值的所有单选按钮均未选中时,以及处于不确定状态的 <progress> 元素
:valid 可以应用约束验证并且当前有效的表单控件。
:invalid 应用了约束验证且当前无效的表单控件。匹配其值与属性设置的约束不匹配的表单控件,例如 requiredpatternstepmax
:in-range 一个非空输入,其当前值在 minmax 属性以及 step 指定的范围限制内。
:out-of-range 非空输入,其当前值不在 minmax 属性指定的范围限制内,或者不遵守 step 约束。
:required 设置了 required 属性的 <input><select><textarea> 元素。仅匹配可能需要的元素。非必需元素上包含的属性不会进行匹配。
:optional 未设置 required 属性的 <input><select><textarea> 元素。不匹配不需要的元素。
:blank 当前没有值的 <input><textarea> 元素。
:user-invalid :invalid 类似,但在模糊时激活。匹配无效输入,但仅在用户交互之后进行,例如通过聚焦于控件、离开控件或尝试提交包含无效控件的表单。

伪类示例

¥Pseudo-classes example

我们可以根据复选框是否被选中来设置复选框标签的样式。在此示例中,我们对紧随检查输入之后出现的 <label>colorfont-weight 进行样式设置。如果未选中 input,我们还没有应用任何样式。

¥We can style a checkbox label based on whether the checkbox is checked or not. In this example, we are styling the color and font-weight of the <label> that comes immediately after a checked input. We haven't applied any styles if the input is not checked.

html
<input id="checkboxInput" type="checkbox" />
<label for="checkboxInput">Toggle the checkbox on and off</label>
css
input:checked + label {
  color: red;
  font-weight: bold;
}

属性选择器

¥Attribute selectors

可以使用 属性选择器 基于 type 来定位不同类型的表单控件。CSS 属性选择器仅根据属性的存在或给定属性的值来匹配元素。

¥It is possible to target different types of form controls based on their type using attribute selectors. CSS attribute selectors match elements based on either just the presence of an attribute or the value of a given attribute.

css
/* matches a password input */
input[type="password"] {
}

/* 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

默认情况下,占位符文本的外观为半透明或浅灰色。::placeholder 伪元素是输入的 placeholder 文字。它可以使用 CSS 属性的有限子集进行样式设置。

¥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;
}

在选择器中使用 ::placeholder 的规则中,只能使用适用于 ::first-line 伪元素的 CSS 属性子集。

¥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.

appearance

appearance 属性允许根据操作系统的主题将(几乎)任何元素显示为平台原生样式,并删除具有 none 值的任何平台原生样式。

¥The appearance property enables the displaying of (almost) any element as a platform-native style based on the operating system's theme as well as the removal of any platform-native styling with the none value.

你可以使 <div> 看起来像带有 div {appearance: radio;} 的单选按钮,或者使单选看起来像带有 [type="radio"] {appearance: checkbox;} 的复选框,但不要这么做。

¥You could make a <div> look like a radio button with div {appearance: radio;} or a radio look like a checkbox with [type="radio"] {appearance: checkbox;}, but don't.

设置 appearance: none 会删除平台原生边界,但不会删除功能。

¥Setting appearance: none removes platform native borders, but not functionality.

caret-color

CSS 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
<label for="textInput">Note the red caret:</label>
<input id="textInput" class="custom" size="32" />

CSS

css
input.custom {
  caret-color: red;
  font:
    16px "Helvetica",
    "Arial",
    "sans-serif";
}

结果

¥Result

field-sizing

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.

此属性通常用于创建表单字段,这些表单字段会收缩其内容并随着输入更多文本而增长。这适用于接受直接文本输入的输入类型(例如,texturl)、输入类型 file<textarea> 元素。

¥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 <textarea> elements.

对象位置和对象配合

¥object-position and object-fit

在某些情况下(通常涉及非文本输入和专用接口),<input> 元素是 被替换的元素。如果是这样,可以使用 CSS object-positionobject-fit 属性来调整元素的位置和大小以及在其框架内的定位。

¥In certain cases (typically involving non-textual inputs and specialized interfaces), the <input> element is a replaced element. When it is, the position and size of the element's size and positioning within its frame can be adjusted using the CSS object-position and object-fit properties.

样式

¥Styling

有关向 HTML 中的元素添加颜色的更多信息,请参阅:

¥For more information about adding color to elements in HTML, see:

另请参阅:

¥Also see:

附加功能

¥Additional features

标签

¥Labels

需要标签将辅助文本与 <input> 关联起来。<label> 元素提供有关始终合适的表单字段的说明信息(除了你所关心的任何布局问题)。使用 <label> 来解释应在 <input><textarea> 中输入的内容绝不是一个坏主意。

¥Labels are needed to associate assistive text with an <input>. The <label> element provides explanatory information about a form field that is always appropriate (aside from any layout concerns you have). It's never a bad idea to use a <label> to explain what should be entered into an <input> or <textarea>.

相关标签

¥Associated labels

<input><label> 元素的语义配对对于屏幕阅读器等辅助技术非常有用。通过使用 <label>for 属性将它们配对,你可以将标签绑定到输入,从而使屏幕阅读器可以更准确地向用户描述输入。

¥The semantic pairing of <input> and <label> elements is useful for assistive technologies such as screen readers. By pairing them using the <label>'s for attribute, you bond the label to the input in a way that lets screen readers describe inputs to users more precisely.

<input> 元素相邻的纯文本是不够的。相反,可用性和可访问性需要包含隐式或显式的 <label>

¥It does not suffice to have plain text adjacent to the <input> element. Rather, usability and accessibility requires the inclusion of either implicit or explicit <label>:

html
<!-- inaccessible -->
<p>Enter your name: <input id="name" type="text" size="30" /></p>

<!-- implicit label -->
<p>
  <label>Enter your name: <input id="name" type="text" size="30" /></label>
</p>

<!-- explicit label -->
<p>
  <label for="name">Enter your name: </label>
  <input id="name" type="text" size="30" />
</p>

第一个示例无法访问:提示和 <input> 元素之间不存在任何关系。

¥The first example is inaccessible: no relationship exists between the prompt and the <input> element.

除了易于访问的名称外,标签还提供了更大的 'hit' 区域,供鼠标和触摸屏用户点击或触摸。通过将 <label><input> 配对,单击任一者都会聚焦 <input>。如果你使用纯文本对输入进行 "label",则不会发生这种情况。输入激活区域的提示部分对于有运动控制条件的人很有帮助。

¥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 <label> with an <input>, clicking on either one will focus the <input>. 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

placeholder 属性允许你指定当 <input> 元素的内容区域为空时出现在该区域本身内的文本。永远不应该要求占位符理解你的表单。它不是标签,也不应该用作替代品,因为它不是。占位符用于提供有关输入值应是什么样子的提示,而不是解释或提示。

¥The placeholder attribute lets you specify text that appears within the <input> 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.

不仅屏幕阅读器无法访问占位符,而且一旦用户在表单控件中输入任何文本,或者表单控件已经有值,占位符就会消失。具有自动页面翻译功能的浏览器在翻译时可能会跳过属性,这意味着 placeholder 可能无法翻译。

¥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.

注意:如果可以避免,请不要使用 placeholder 属性。如果需要标记 <input> 元素,请使用 <label> 元素。

¥Note: Don't use the placeholder attribute if you can avoid it. If you need to label an <input> element, use the <label> element.

客户端验证

¥Client-side validation

警告:客户端验证很有用,但它不能保证服务器会收到有效的数据。如果数据必须采用特定格式,请始终在服务器端验证它,如果格式无效,则返回 400 HTTP 响应

¥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.

除了使用 CSS 根据每个输入当前状态的 :valid:invalid UI 状态设置输入样式(如上面 UI 伪类 部分所述)之外,浏览器还提供对(尝试的)表单提交的客户端验证。表单提交时,如果存在未通过约束验证的表单控件,支持的浏览器将在第一个无效的表单控件上显示错误消息;根据错误类型显示默认消息或你设置的消息。

¥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.

某些输入类型和其他属性对给定输入的有效值进行了限制。例如,<input type="number" min="2" max="10" step="2"> 表示仅数字 2、4、6、8 或 10 有效。可能会出现多个错误,包括如果值小于 2,则出现 rangeUnderflow 错误;如果大于 10,则出现 rangeOverflow;如果值是 2 到 10 之间的数字,但不是偶数,则出现 stepMismatch 错误(不符合 step 属性的要求) ),如果该值不是数字,则为 typeMismatch

¥Some input types and other attributes place limits on what values are valid for a given input. For example, <input type="number" min="2" max="10" step="2"> 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.

对于可能值的域是周期性的输入类型(即,在最高可能值时,值回绕到开头而不是结尾),maxmin 属性的值可能会颠倒,这 指示允许值的范围从 min 开始,回绕到可能的最低值,然后继续直至达到 max。这对于日期和时间特别有用,例如当你希望允许范围为晚上 8 点到上午 8 点时:

¥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
<input type="time" min="20:00" max="08:00" name="overnight" />

特定属性及其值可能导致特定错误 ValidityState

¥Specific attributes and their values can lead to a specific error ValidityState:

Validity object errors depend on the <input> attributes and their values:
属性 相关属性 描述
max validityState.rangeOverflow 当值大于 max 属性定义的最大值时发生
maxlength validityState.tooLong 当字符数大于 maxlength 属性允许的数量时发生
min validityState.rangeUnderflow 当值小于 min 属性定义的最小值时发生
minlength validityState.tooShort 当字符数小于 minlength 属性所需的数量时发生
pattern validityState.patternMismatch 当模式属性包含在有效的正则表达式中并且 value 与它不匹配时发生。
required validityState.valueMissing required 属性存在但值为 null 或未选中单选或复选框时发生。
step validityState.stepMismatch 该值与步长增量不匹配。增量默认为 XSPACE1,因此只有整数在 type="number" 上有效,不包括步骤。 step="any" 永远不会抛出此错误。
type validityState.typeMismatch 当值的类型不正确时发生,例如电子邮件不包含 @ 或 url 不包含协议。

如果表单控件没有 required 属性,则任何值或空字符串都不是无效的。即使存在上述属性,除了 required 之外,空字符串也不会导致错误。

¥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.

除了上表中描述的错误之外,validityState 接口还包含 badInputvalidcustomError 布尔只读属性。有效性对象包括:

¥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:

对于其中每个布尔属性,值 true 表示指定的验证可能失败的原因为 true,但 valid 属性除外,如果元素的值遵守所有约束,则该属性为 true

¥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.

如果出现错误,支持的浏览器将警告用户并阻止表单提交。温馨提示:如果自定义错误设置为真值(空字符串或 null 以外的任何值),则将阻止提交表单。如果没有自定义错误消息,并且其他属性均不返回 true,则 valid 将为 true,并且可以提交表单。

¥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_object = input.validity;
  if (validityState_object.valueMissing) {
    input.setCustomValidity("A value is required");
  } else if (validityState_object.rangeUnderflow) {
    input.setCustomValidity("Your value is too low");
  } else if (validityState_object.rangeOverflow) {
    input.setCustomValidity("Your value is too high");
  } else {
    input.setCustomValidity("");
  }
}

最后一行,将自定义有效性消息设置为空字符串至关重要。如果用户出错,并且设置了有效性,即使所有值都有效,也将无法提交,直到消息为 null

¥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

如果你想在字段验证失败时显示自定义错误消息,则需要使用 <input>(及相关)元素上可用的 约束验证 API。采用以下形式:

¥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 <input> (and related) elements. Take the following form:

html
<form>
  <label for="name">Enter username (upper and lowercase letters): </label>
  <input type="text" name="name" id="name" required pattern="[A-Za-z]+" />
  <button>Submit</button>
</form>

如果你尝试提交未填写有效内容或值与 pattern 不匹配的表单,基本 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.

如果你想显示自定义错误消息,你可以使用 JavaScript,如下所示:

¥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:

  • 每次输入元素的值发生更改时,我们都会通过 input 事件处理程序运行 checkValidity() 方法来检查输入元素的有效状态。
  • 如果该值无效,则会引发 invalid 事件,并运行 invalid 事件处理函数。在此函数内,我们使用 if () 块计算该值是否无效,因为它为空,或者因为它与模式不匹配,并设置自定义有效性错误消息。
  • 因此,如果按下提交按钮时输入值无效,则会显示自定义错误消息之一。
  • 如果有效,它将按你的预期提交。为此,必须通过使用空字符串值调用 setCustomValidity() 来取消自定义有效性。因此,每次引发 input 事件时,我们都会执行此操作。如果你不这样做,并且之前设置了自定义有效性,则输入将注册为无效,即使它当前在提交时包含有效值。

注意:始终验证客户端和服务器端的输入约束。约束验证并不能消除服务器端验证的需要。旧版浏览器或不良行为者仍可能发送无效值。

¥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.

注意:Firefox 在许多版本中都支持专有的错误属性 - x-moz-errormessage,它允许你以类似的方式设置自定义错误消息。从版本 66 开始,这已被删除(参见 火狐错误 1513890)。

¥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

某些 <input> 类型允许的输入取决于区域设置。在某些区域设置中,1,000.00 是有效数字,而在其他区域设置中,输入该数字的有效方式是 1.000,00。

¥The allowed inputs for certain <input> 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 使用以下启发式方法来确定区域设置以验证用户的输入(至少对于 type="number"):

¥Firefox uses the following heuristics to determine the locale to validate the user's input (at least for type="number"):

  • 尝试由元素或其任何父元素上的 lang/xml:lang 属性指定的语言。
  • 尝试任何 Content-Language HTTP 标头指定的语言。或者,
  • 如果未指定,则使用浏览器的区域设置。

技术总结

¥Technical summary

内容类别 流量内容,列出的、可提交的、可重置的、表单关联的元素, 措辞内容。如果 type 不是 hidden,则可标记元素,可感知内容。
允许的内容 没有任何;这是 void element
标签遗漏 必须有开始标记,并且不能有结束标记。
允许的父级 任何接受 措辞内容 的元素。
隐式 ARIA 角色
允许的 ARIA 角色
DOM 接口 HTMLInputElement

无障碍问题

¥Accessibility concerns

标签

¥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 .

以下是如何将上述样式中的 <label><input> 元素关联起来的示例。你需要为 <input> 赋予 id 属性。然后,<label> 需要一个 for 属性,其值与输入的 id 相同。

¥The following is an example of how to associate the <label> with an <input> element in the above style. You need to give the <input> an id attribute. The <label> then needs a for attribute whose value is the same as the input's id.

html
<label for="peas">Do you like peas?</label>
<input type="checkbox" name="peas" id="peas" />

尺寸

¥Size

诸如表单输入之类的交互元素应该提供足够大的区域,以便于激活它们。这对各种各样的人都有帮助,包括有运动控制问题的人以及使用手写笔或手指等非精确输入形式的人。建议最小交互尺寸为 44×44 CSS 像素

¥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.

规范

Specification
HTML Standard
# the-input-element

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看