<input> elements of type password provide a way for the user to securely enter a password. 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 用户代理 and OS .

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

Specifics of how the entry process works may vary from browser to browser; mobile devices, for example, often display the typed character for a moment before obscuring it, to allow the user to be sure they pressed the key they meant to press; this is helpful given the small size of keys and the ease with which the wrong one can be pressed, especially on virtual keyboards.

注意: Any forms involving sensitive information like passwords (e.g. login forms) should be served over HTTPS; Many browsers now implement mechanisms to warn against insecure login forms; see Insecure passwords .

A DOMString representing a password, or empty
事件 change and input
Supported Common Attributes autocomplete , inputmode , maxlength , minlength , pattern , placeholder , readonly , required ,和 size
IDL attributes selectionStart , selectionEnd , selectionDirection ,和 value
方法 select() , setRangeText() ,和 setSelectionRange()

value attribute contains a DOMString 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 attribute is specified, the content of a password control is only considered valid if the value passes validation; see 验证 了解更多信息。

注意: 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.

Additional attributes

In addition to the attributes that operate on all <input> elements regardless of their type, password field inputs support the following attributes:

属性 描述
maxlength The maximum length the value may be, in UTF-16 characters
minlength The minimum length in characters that will be considered valid
pattern A regular expression the value must match in order to be valid
placeholder An example value to display in the field when the field is empty
readonly A Boolean attribute which, if present, indicates that the field's contents should not be editable
size The number of characters wide the input field should be

maxlength

The maximum number of characters (as UTF-16 code units) the user can enter into the password field. This must be an integer value 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 .

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.

minlength

The minimum number of characters (as UTF-16 code units) the user can enter into the password entry field. This must be an 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.

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.

pattern

pattern attribute, when specified, is 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 '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 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 验证 for details and an example.

placeholder

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 不必 include carriage returns or line feeds.

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 Overriding BiDi using Unicode control characters in The Unicode Bidirectional Text Algorithm for those characters.

注意: 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 Labels and placeholders in <input>: The Input (Form Input) element 了解更多信息。

readonly

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 特性。

注意: Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified.

size

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

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 属性。

Using password inputs

Password input boxes generally work just like other textual input boxes; the main difference is the obscuring of the content to prevent people near the user from reading the password.

A simple password input

Here we see the most basic password input, with a label established using the <label> 元素。

<label for="userPassword">Password: </label>
<input id="userPassword" type="password">

Allowing 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
Allow the browser or a password manager to automatically fill out the password field. This isn't as informative as using either current-password or new-password .
off

Don't allow the browser or password manager to automatically fill out the password field. Note that some software ignores this value, since it's typically harmful to users' ability to maintain safe password practices.

current-password
Allow the browser or password manager to enter the current password for the site. This provides more information than on does, since it lets the browser or password manager automatically enter currently-known password for the site in the field, but not to suggest a new one.
new-password

Allow the browser or password manager to automatically enter a new password for the site; this is used on "change your password" and "new user" forms, on the field asking the user for a new password. The new password may be generated in a variety of ways, depending on the password manager in use. It may simply fill in a new suggested password, or it might show the user an interface for creating one.

<label for="userPassword">Password:</label>
<input id="userPassword" type="password" autocomplete="current-password">

Making the password mandatory

To tell the user's browser that the password field must have a valid value before the form can be submitted, simply specify the Boolean required 属性。

<label for="userPassword">Password: </label>
<input id="userPassword" type="password" required>
<input type="submit" value="Submit">

Specifying an input mode

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

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

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 = function() {
  document.getElementById("userPassword").select();
}

结果

还可以使用 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.

验证

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">

被禁用

This Boolean attribute indicates that the password field is not available for interaction. Additionally, disabled field values aren't submitted with the form.

范例

Requesting a Social Security number

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>

This uses a pattern which limits the entered value to strings representing legal Socal 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 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 被设为 off to avoid password managers and session restore features trying to set its value, since this isn't a password at all.

JavaScript

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 .

var ssn = document.getElementById("ssn");
var current = document.getElementById("current");
ssn.oninput = function(event) {
  current.innerHTML = ssn.value;
}

结果

规范

规范 状态 注释
HTML 实时标准
The definition of '<input type="password">' in that specification.
实时标准 初始定义
HTML 5.1
The definition of '<input type="password">' in that specification.
推荐 初始定义

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
type="password" Chrome 完整支持 1 Edge 完整支持 12 Firefox 完整支持 1 IE 完整支持 2 Opera 完整支持 2 Safari 完整支持 1 WebView Android ? Chrome Android 完整支持 Yes Firefox Android 完整支持 4 Opera Android 完整支持 Yes Safari iOS 完整支持 Yes Samsung Internet Android 完整支持 Yes
Special handling of password inputs in insecure login pages 非标 Chrome 不支持 No Edge 不支持 No Firefox 完整支持 52 IE 不支持 No Opera 不支持 No Safari 不支持 No WebView Android 不支持 No Chrome Android 不支持 No Firefox Android 完整支持 52 Opera Android 不支持 No Safari iOS 不支持 No Samsung Internet Android 不支持 No

图例

完整支持

完整支持

不支持

不支持

兼容性未知 ?

兼容性未知

非标。预期跨浏览器支持较差。

非标。预期跨浏览器支持较差。

另请参阅

元数据

  • 最后修改:
  1. <button>
  2. <datalist>
  3. <fieldset>
  4. <form>
  5. <input>
  6. <label>
  7. <legend>
  8. <meter>
  9. <optgroup>
  10. <option>
  11. <output>
  12. <progress>
  13. <select>
  14. <textarea>
  15. <input> 类型
    1. <input type="button">
    2. <input type="checkbox">
    3. <input type="color">
    4. <input type="date">
    5. <input type="datetime">
    6. <input type="datetime-local">
    7. <input type="email">
    8. <input type="file">
    9. <input type="hidden">
    10. <input type="image">
    11. <input type="month">
    12. <input type="number">
    13. <input type="password">
    14. <input type="radio">
    15. <input type="range">
    16. <input type="reset">
    17. <input type="search">
    18. <input type="submit">
    19. <input type="tel">
    20. <input type="text">
    21. <input type="time">
    22. <input type="url">
    23. <input type="week">
  16. HTML 元素
    1. A
      1. <a>
      2. <abbr>
      3. <acronym>
      4. <address>
      5. <applet>
      6. <area>
      7. <article>
      8. <aside>
      9. <audio>
    2. B
      1. <b>
      2. <base>
      3. <basefont>
      4. <bdi>
      5. <bdo>
      6. <bgsound>
      7. <big>
      8. <blink>
      9. <blockquote>
      10. <body>
      11. <br>
      12. <button>
    3. C
      1. <canvas>
      2. <caption>
      3. <center>
      4. <cite>
      5. <code>
      6. <col>
      7. <colgroup>
      8. <content>
    4. D
      1. <data>
      2. <datalist>
      3. <dd>
      4. <del>
      5. <details>
      6. <dfn>
      7. <dialog>
      8. <dir>
      9. <div>
      10. <dl>
      11. <dt>
    5. E
      1. <em>
      2. <embed>
    6. F
      1. <fieldset>
      2. <figcaption>
      3. <figure>
      4. <font>
      5. <footer>
      6. <form>
      7. <frame>
      8. <frameset>
    7. G H
      1. <h1>
      2. <h2>
      3. <h3>
      4. <h4>
      5. <h5>
      6. <h6>
      7. <head>
      8. <header>
      9. <hgroup>
      10. <hr>
      11. <html>
    8. I
      1. <i>
      2. <iframe>
      3. <img>
      4. <input>
      5. <ins>
      6. <isindex>
    9. J K
      1. <kbd>
      2. <keygen>
    10. L
      1. <label>
      2. <legend>
      3. <li>
      4. <link>
      5. <listing>
    11. M
      1. <main>
      2. <map>
      3. <mark>
      4. <marquee>
      5. <menu>
      6. <menuitem>
      7. <meta>
      8. <meter>
    12. N
      1. <nav>
      2. <nobr>
      3. <noframes>
      4. <noscript>
    13. O
      1. <object>
      2. <ol>
      3. <optgroup>
      4. <option>
      5. <output>
    14. P
      1. <p>
      2. <param>
      3. <picture>
      4. <plaintext>
      5. <pre>
      6. <progress>
    15. Q
      1. <q>
    16. R
      1. <rp>
      2. <rt>
      3. <rtc>
      4. <ruby>
    17. S
      1. <s>
      2. <samp>
      3. <script>
      4. <section>
      5. <select>
      6. <shadow>
      7. <slot>
      8. <small>
      9. <source>
      10. <spacer>
      11. <span>
      12. <strike>
      13. <strong>
      14. <style>
      15. <sub>
      16. <summary>
      17. <sup>
    18. T
      1. <table>
      2. <tbody>
      3. <td>
      4. <template>
      5. <textarea>
      6. <tfoot>
      7. <th>
      8. <thead>
      9. <time>
      10. <title>
      11. <tr>
      12. <track>
      13. <tt>
    19. U
      1. <u>
      2. <ul>
    20. V
      1. <var>
      2. <video>
    21. W
      1. <wbr>
    22. X Y Z
      1. <xmp>

版权所有  © 2014-2026 乐数软件    

工业和信息化部: 粤ICP备14079481号-1