<input type="password">
password
类型的 <input>
元素为用户提供了一种安全输入密码的方法。
¥<input>
elements of type password
provide a way for the user to securely enter a password.
该元素以单行纯文本编辑器控件的形式呈现,其中的文本被遮蔽以致无法读取,通常通过将每个字符替换为星号 ("*") 或点 ("•") 等符号来实现。该字符将根据 user agent 和操作系统的不同而有所不同。
¥The element is presented as a one-line plain text editor control in which the text is obscured so that it cannot be read, usually by replacing each character with a symbol such as the asterisk ("*") or a dot ("•"). This character will vary depending on the user agent and operating system.
Try it
输入过程的精确行为可能因浏览器而异。某些浏览器会先显示键入的字符一段时间,然后再将其隐藏,而另一些浏览器则允许用户打开和关闭纯文本的显示。这两种方法都可以帮助用户检查他们是否输入了预期的密码,这在移动设备上尤其困难。
¥The precise behavior of the entry process may vary from browser to browser. Some browsers display the typed character for a moment before obscuring it, while others allow the user to toggle the display of plain-text on and off. Both approaches help a user check that they entered the intended password, which can be particularly difficult on mobile devices.
注意:任何涉及密码等敏感信息的表单(例如登录表单)都应通过 HTTPS 提供服务。许多浏览器现在都实现了警告不安全登录表单的机制;见 密码不安全。
¥Note: Any forms involving sensitive information like passwords (such as login forms) should be served over HTTPS. Many browsers now implement mechanisms to warn against insecure login forms; see Insecure passwords.
值
¥Value
value
属性包含一个字符串,其值是用于输入密码的文本编辑控件的当前内容。如果用户尚未输入任何内容,则该值为空字符串 (""
)。如果指定了 required
属性,则密码编辑框必须包含空字符串以外的值才有效。
¥The value
attribute contains a string whose value is the current contents of the text editing control being used to enter the password. If the user hasn't entered anything yet, this value is an empty string (""
). If the required
property is specified, then the password edit box must contain a value other than an empty string to be valid.
如果指定了 pattern
属性,则仅当值通过验证时,password
控件的内容才被视为有效;请参阅 验证 了解更多信息。
¥If the pattern
attribute is specified, the content of a password
control is only considered valid if the value passes validation; see Validation for more information.
注意:
password
值中不允许使用换行符 (U+000A) 和回车符 (U+000D)。设置密码控件的值时,换行符和回车符将从值中去除。¥Note: The line feed (U+000A) and carriage return (U+000D) characters are not permitted in a
password
value. When setting the value of a password control, line feed and carriage return characters are stripped out of the value.
附加属性
maxlength
用户可以在密码字段中输入的最大字符串长度(以 UTF-16 代码单位测量)。这必须是 0 或更大的整数值。如果未指定 maxlength
,或者指定了无效值,则密码字段没有最大长度。该值还必须大于或等于 minlength
的值。
¥The maximum string length (measured in UTF-16 code units) that the user can enter into the password field. This must be an integer value of 0 or higher. If no maxlength
is specified, or an invalid value is specified, the password field has no maximum length. This value must also be greater than or equal to the value of minlength
.
如果输入字段的文本长度大于 maxlength
UTF-16 代码单元长度,则输入将失败 约束验证。仅当用户更改值时才应用约束验证。
¥The input will fail constraint validation if the length of the text entered into the field is greater than maxlength
UTF-16 code units long. Constraint validation is only applied when the value is changed by the user.
minlength
用户可以在密码输入字段中输入的最小字符串长度(以 UTF-16 代码单位测量)。该值必须是小于或等于 maxlength
指定值的非负整数值。如果未指定 minlength
,或者指定了无效值,则输入的密码没有最小长度。
¥The minimum string length (measured in UTF-16 code units) that the user can enter into the password entry field. This must be a non-negative integer value smaller than or equal to the value specified by maxlength
. If no minlength
is specified, or an invalid value is specified, the password input has no minimum length.
如果输入字段的文本长度小于 minlength
UTF-16 代码单元长度,则输入将失败 约束验证。仅当用户更改值时才应用约束验证。
¥The input will fail constraint validation if the length of the text entered into the field is fewer than minlength
UTF-16 code units long. Constraint validation is only applied when the value is changed by the user.
pattern
指定时,pattern
属性是一个正则表达式,输入的 value
必须与该正则表达式匹配才能传递 约束验证 的值。它必须是有效的 JavaScript 正则表达式,如 RegExp
类型所使用的,以及我们的 正则表达式指南 中记录的;编译正则表达式时指定 'u'
标志,以便将模式视为 Unicode 代码点序列,而不是 ASCII。模式文本周围不应指定正斜杠。
¥The pattern
attribute, when specified, is a regular expression that the input's value
must match 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; the 'u'
flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text.
如果指定的模式未指定或无效,则不应用正则表达式,并且完全忽略该属性。
¥If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely.
注意:使用
title
属性指定大多数浏览器将显示为工具提示的文本,以解释匹配模式的要求。你还应该在附近添加其他解释性文字。¥Note: Use the
title
attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby.
强烈建议在密码输入中使用模式,以帮助确保用户选择和使用使用各种字符类的有效密码。使用模式,你可以强制执行大小写规则,要求使用一定数量的数字和/或标点符号,等等。有关详细信息和示例,请参阅第 验证 节。
¥Use of a pattern is strongly recommended for password inputs, in order to help ensure that valid passwords using a wide assortment of character classes are selected and used by your users. With a pattern, you can mandate case rules, require the use of some number of digits and/or punctuation characters, and so forth. See the section Validation for details and an example.
placeholder
placeholder
属性是一个字符串,向用户提供有关该字段中期望的信息类型的简短提示。它应该是一个单词或短语,展示预期的数据类型,而不是解释性消息。文本不得包含回车或换行。
¥The placeholder
attribute is a string that 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 demonstrates the expected type of data, rather than an explanatory message. The text must not include carriage returns or line feeds.
如果控件的内容具有一个方向性(LTR 或 RTL),但需要以相反的方向性呈现占位符,则可以使用 Unicode 双向算法格式化字符来覆盖占位符内的方向性;请参阅 如何使用 Bidi 文本的 Unicode 控件 了解更多信息。
¥If the control's content has one directionality (LTR or RTL) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see How to use Unicode controls for bidi text for more information.
注意:如果可以的话,请避免使用
placeholder
属性。它在语义上不如解释表单的其他方法那么有用,并且可能会导致内容出现意外的技术问题。请参阅<input>
标签 了解更多信息。¥Note: Avoid using the
placeholder
attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See<input>
labels for more information.
readonly
布尔属性,如果存在,则意味着用户无法编辑该字段。然而,它的 value
仍然可以通过直接设置 HTMLInputElement.value
属性值的 JavaScript 代码进行更改。
¥A Boolean attribute which, if present, means this field cannot be edited by the user. Its value
can, however, still be changed from JavaScript code that directly sets the value of the HTMLInputElement.value
property.
注意:由于只读字段不能有值,因此
required
对同时指定了readonly
属性的输入没有任何影响。¥Note: Because a read-only field cannot have a value,
required
does not have any effect on inputs with thereadonly
attribute also specified.
size
size
属性是一个数值,指示输入字段应有多少个字符宽。该值必须是大于零的数字,默认值为 20。由于字符宽度各不相同,因此这可能准确,也可能不准确,因此不应依赖于此;结果输入可能比指定的字符数更窄或更宽,具体取决于字符和字体(使用的 font
设置)。
¥The size
attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since character widths vary, this may or may not be exact and should not be relied upon to be so; the resulting input may be narrower or wider than the specified number of characters, depending on the characters and the font (font
settings in use).
这不会限制用户可以在该字段中输入的字符数。它仅指定一次大约可以看到多少个。要设置输入数据长度的上限,请使用 maxlength
属性。
¥This does not set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the maxlength
attribute.
使用密码输入
简单的密码输入
允许自动补齐
¥Allowing autocomplete
要允许用户的密码管理器自动输入密码,请指定 autocomplete
属性。对于密码,通常应为以下之一:
¥To allow the user's password manager to automatically enter the password, specify the autocomplete
attribute. For passwords, this should typically be one of the following:
on
-
允许浏览器或密码管理器自动填写密码字段。这不像使用
current-password
或new-password
那样提供信息。 off
-
不允许浏览器或密码管理器自动填写密码字段。请注意,某些软件会忽略此值,因为它通常会损害用户维护安全密码实践的能力。
current-password
-
允许浏览器或密码管理器输入站点的当前密码。这提供了比
on
更多的信息,因为它允许浏览器或密码管理器自动在字段中输入当前已知的站点密码,但不会建议新密码。 new-password
-
允许浏览器或密码管理器自动输入网站的新密码;这用于 "更改你的密码" 和 "新用户" 表单,在要求用户输入新密码的字段中。新密码可以通过多种方式生成,具体取决于所使用的密码管理器。它可能会填写新的建议密码,也可能会向用户显示用于创建密码的界面。
<label for="userPassword">Password:</label>
<input id="userPassword" type="password" autocomplete="current-password" />
强制输入密码
¥Making the password mandatory
要告诉用户的浏览器密码字段必须具有有效值才能提交表单,请指定布尔值 required
属性。
¥To tell the user's browser that the password field must have a valid value before the form can be submitted, specify the Boolean required
attribute.
<label for="userPassword">Password: </label>
<input id="userPassword" type="password" required />
<input type="submit" value="Submit" />
指定输入模式
¥Specifying an input mode
如果你推荐的(或必需的)密码语法规则将受益于标准键盘之外的替代文本输入界面,则你可以使用 inputmode
属性来请求特定的文本输入界面。最明显的用例是密码需要为数字(例如 PIN)。例如,具有虚拟键盘的移动设备可能会选择切换到数字键盘布局而不是完整键盘,以便更轻松地输入密码。如果 PIN 码是一次性使用的,请将 autocomplete
属性设置为 off
或 one-time-code
,以表明不保存该 PIN 码。
¥If your recommended (or required) password syntax rules would benefit from an alternate text entry interface than the standard keyboard, you can use the inputmode
attribute to request a specific one. The most obvious use case for this is if the password is required to be numeric (such as a PIN). Mobile devices with virtual keyboards, for example, may opt to switch to a numeric keypad layout instead of a full keyboard, to make entering the password easier. If the PIN is for one-time use, set the autocomplete
attribute to either off
or one-time-code
to suggest that it's not saved.
<label for="pin">PIN: </label>
<input id="pin" type="password" inputmode="numeric" />
设置长度要求
¥Setting length requirements
像往常一样,你可以使用 minlength
和 maxlength
属性来确定密码的最小和最大可接受长度。此示例对前一个示例进行了扩展,指定用户的 PIN 必须至少为四位且不超过八位。size
属性用于确保密码输入控件的宽度为八个字符。
¥As usual, you can use the minlength
and maxlength
attributes to establish minimum and maximum acceptable lengths for the password. This example expands on the previous one by specifying that the user's PIN must be at least four and no more than eight digits. The size
attribute is used to ensure that the password entry control is eight characters wide.
<label for="pin">PIN:</label>
<input
id="pin"
type="password"
inputmode="numeric"
minlength="4"
maxlength="8"
size="8" />
选择文本
¥Selecting text
与其他文本输入控件一样,你可以使用 select()
方法选择密码字段中的所有文本。
¥As with other textual entry controls, you can use the select()
method to select all the text in the password field.
HTML
<label for="userPassword">Password: </label>
<input id="userPassword" type="password" size="12" />
<button id="selectAll">Select All</button>
JavaScript
document.getElementById("selectAll").onclick = () => {
document.getElementById("userPassword").select();
};
结果
¥Result
你还可以使用 selectionStart
和 selectionEnd
来获取(或设置)当前选择的控件中的字符范围,并使用 selectionDirection
来了解发生在哪个方向选择(或将扩展到哪个方向,具体取决于你的平台;请参阅其文档以获取解释)。然而,由于文字模糊,这些内容的用处受到一定限制。
¥You can also use selectionStart
and selectionEnd
to get (or set) what range of characters in the control are currently selected, and selectionDirection
to know which direction selection occurred in (or will be extended in, depending on your platform; see its documentation for an explanation). However, given that the text is obscured, the usefulness of these is somewhat limited.
验证
¥Validation
如果你的应用对输入密码的实际内容有字符集限制或任何其他要求,你可以使用 pattern
属性建立一个正则表达式,用于自动确保你的密码满足这些要求。
¥If your application has character set restrictions or any other requirement for the actual content of the entered password, you can use the pattern
attribute to establish a regular expression to be used to automatically ensure that your passwords meet those requirements.
在此示例中,只有由至少四个且不超过八个十六进制数字组成的值才有效。
¥In this example, only values consisting of at least four and no more than eight hexadecimal digits are valid.
<label for="hexId">Hex ID: </label>
<input
id="hexId"
type="password"
pattern="[0-9a-fA-F]{4,8}"
title="Enter an ID consisting of 4-8 hexadecimal digits"
autocomplete="new-password" />
示例
申请社会安全号码
¥Requesting a Social Security number
此示例仅接受与 有效的美国社会安全号码 格式匹配的输入。这些号码在美国用于税务和身份识别目的,格式为 "123-45-6789"。还存在关于每个组中允许哪些值的各种规则。
¥This example only accepts input which matches the format for a valid United States Social Security Number. These numbers, used for tax and identification purposes in the US, are in the form "123-45-6789". Assorted rules for what values are permitted in each group exist as well.
HTML
<label for="ssn">SSN:</label>
<input
type="password"
id="ssn"
inputmode="numeric"
minlength="9"
maxlength="12"
pattern="(?!000)([0-6]\d{2}|7([0-6]\d|7[012]))([ -])?(?!00)\d\d\3(?!0000)\d{4}"
required
autocomplete="off" />
<br />
<label for="ssn">Value:</label>
<span id="current"></span>
这使用 pattern
将输入的值限制为代表合法社会安全号码的字符串。显然,这个正则表达式不能保证 SSN 有效(因为我们无法访问社会保障管理局的数据库),但它确实确保该数字可能是 1;它通常会避免无效的值。此外,它允许三组数字用空格、破折号 ("*") 或什么都不分隔。
¥This uses a pattern
which limits the entered value to strings representing legal Social Security numbers. Obviously, this regexp doesn't guarantee a valid SSN (since we don't have access to the Social Security Administration's database), but it does ensure the number could be one; it generally avoids values that cannot be valid. In addition, it allows the three groups of digits to be separated by a space, a dash ("-"), or nothing.
inputmode
设置为 numeric
是为了鼓励具有虚拟键盘的设备切换到数字键盘布局,以便于输入。minlength
和 maxlength
属性分别设置为 9 和 12,要求该值至少为 9 个且不超过 12 个字符(前者在数字组之间不分隔字符,后者在数字组之间分隔字符)。required
属性用于指示该控件必须有一个值。最后,autocomplete
设置为 off
以避免密码管理器和会话恢复功能尝试设置其值,因为这根本不是密码。
¥The inputmode
is set to numeric
to encourage devices with virtual keyboards to switch to a numeric keypad layout for easier entry. The minlength
and maxlength
attributes are set to 9 and 12, respectively, to require that the value be at least nine and no more than 12 characters (the former without separating characters between the groups of digits and the latter with them). The required
attribute is used to indicate that this control must have a value. Finally, autocomplete
is set to off
to avoid password managers and session restore features trying to set its value, since this isn't a password at all.
JavaScript
这只是一些简单的代码,用于在屏幕上显示输入的 SSN,以便你可以看到它。显然,这违背了密码字段的目的,但它对于试验 pattern
很有帮助。
¥This is just some simple code to display the entered SSN onscreen so you can see it. Obviously this defeats the purpose of a password field, but it's helpful for experimenting with the pattern
.
const ssn = document.getElementById("ssn");
const current = document.getElementById("current");
ssn.oninput = (event) => {
current.textContent = ssn.value;
};
结果
¥Result
技术总结
¥Technical summary
值 | 代表密码的字符串,或者为空 |
活动 | change 和 input |
支持的通用属性 |
autocomplete 、
inputmode 、
maxlength 、
minlength 、
pattern 、
placeholder 、
readonly 、
required 和
size
|
IDL 属性 |
selectionStart 、 selectionEnd 、
selectionDirection 和 value
|
DOM 接口 | |
方法 | select() 、setRangeText() 和 setSelectionRange() |
隐式 ARIA 角色 | no corresponding role |
规范
Specification |
---|
HTML Standard # password-state-(type=password) |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also