EthicsComputerCourses
Join training +91 90532 10052

Password & Credential Autocomplete

HTML · Lesson 172 of 234 Advanced 11 min read Updated

By the end of this lesson you will be able to write any autocomplete value correctly, mark up login, change-password and Indian address forms so browsers and password managers fill them perfectly, and run a script that finds every field with a missing or broken value.

What you should know first: Advanced Form Attributes and Form Validation Basics, where you met common autocomplete values, and Secure Authentication Form Design, which built the login, sign-up and OTP forms this lesson fine-tunes.

How browsers decide what to fill

Picture a kitchen with unlabelled steel dabbas. A guest has to open each one and sniff to find the salt. Label them and anyone finds it in a second. Form fields are the same. Without autocomplete, the browser guesses from names, labels and position. The guesses fail often: name="txtField3" tells it nothing. An explicit token removes the guessing.

Correct tokens matter for three reasons:

  • Speed. A 12-field checkout fills in one tap.
  • Security. Password managers fill only the right site and generate strong passwords for new-password fields.
  • Accessibility. WCAG 1.3.5 Identify Input Purpose (AA) asks that fields collecting user data expose their purpose, and autocomplete is the standard way. People with memory or motor difficulties rely on autofill.

The token grammar

An autocomplete value is a list of space-separated tokens in a fixed order. The HTML standard defines four slots:

SlotOptional?TokensExample
1. SectionOptionalsection- followed by any namesection-gift
2. Address typeOptionalshipping or billingshipping
3. FieldRequiredA field name, or home, work, mobile, fax or pager followed by a contact fieldpostal-code, work email
4. CredentialOptionalwebauthn (input and textarea only)username webauthn

A full example: autocomplete="section-gift shipping postal-code". Tokens are case-insensitive. The keywords on and off must stand alone.

Field names fall into groups:

GroupField names
Name and identityname, given-name, additional-name, family-name, honorific-prefix, nickname, organization, organization-title, sex, language
Credentialsusername, current-password, new-password, one-time-code
Addressstreet-address, address-line1 to address-line3, address-level1 to address-level4, postal-code, country, country-name
Paymentcc-name, cc-given-name, cc-family-name, cc-number, cc-exp, cc-exp-month, cc-exp-year, cc-csc, cc-type, transaction-currency, transaction-amount
Otherbday, bday-day, bday-month, bday-year, url, photo
Contact (accept home, work, mobile...)tel, tel-country-code, tel-national, tel-area-code, tel-local, tel-extension, email, impp

Only contact fields take the home/work/mobile prefix. So work email is valid, but home postal-code is not.

section-* separates groups that would otherwise clash. A form that sends a parcel to two people needs two sets of shipping fields. With section-1 and section-2, the browser fills each group from a different saved address.

Step 1: let the browser check your tokens

You do not need to memorise the rules. Every input has an autocomplete property (the IDL attribute) that returns the cleaned-up value when the tokens are valid and an empty string "" when they are not. The tester below uses that. Try the presets, then type your own.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Autocomplete token tester</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; max-inline-size: 34rem; }
    input, select { font-size: 1rem; padding: 6px; inline-size: 100%; box-sizing: border-box; }
    label { display: block; margin-block-start: 10px; font-weight: bold; }
    #verdict { font-size: 1.1rem; }
    .ok { color: #166534; } .bad { color: #b91c1c; }
  </style>
</head>
<body>
  <h1>Is this autocomplete value valid?</h1>
  <label for="preset">Presets</label>
  <select id="preset">
    <option>Shipping Postal-Code</option>
    <option>section-gift shipping postal-code</option>
    <option>work email</option>
    <option>home postal-code</option>
    <option>username webauthn</option>
    <option>webauthn username</option>
    <option>billing shipping street-address</option>
    <option>new-password off</option>
    <option>pincode</option>
  </select>
  <label for="value">Value to test</label>
  <input id="value" spellcheck="false">
  <p id="verdict" role="status"></p>

  <script>
    const probe = document.createElement("input");   // never shown; used only for checking
    const box = document.querySelector("#value");
    const verdict = document.querySelector("#verdict");

    function test() {
      probe.setAttribute("autocomplete", box.value);
      const result = probe.autocomplete;               // "" means the browser rejected it
      verdict.className = result ? "ok" : "bad";
      verdict.textContent = result
        ? `Valid. The browser reads it as "${result}".`
        : "Invalid. The browser returns an empty string and falls back to guessing.";
    }
    document.querySelector("#preset").addEventListener("change", (event) => {
      box.value = event.target.value;
      test();
    });
    box.addEventListener("input", test);
    box.value = document.querySelector("#preset").value;
    test();
  </script>
</body>
</html>

In Chrome 157 we got: Shipping Postal-Code is valid and becomes shipping postal-code. home postal-code is invalid, because postal codes are not contact fields. webauthn username is invalid, because webauthn must come last. billing shipping is invalid (only one address type), and so is pincode, which is not a real token.

Credential tokens in detail

TokenUse it onWhat the password manager does
usernameThe login identifier, even if it is an email or mobile numberFills the saved login and pairs it with the password
current-passwordLogin and "confirm it's you" formsFills the saved password
new-passwordSign-up, change and reset forms, both boxes if you ask twiceOffers a strong generated password and saves it
one-time-codeOTP and verification codesOffers a code from SMS or the password manager's authenticator
webauthn (last)The username field of a loginShows saved passkeys in the autofill list

Use username, not email, on login forms, even when the username is an email. email is for contact details, such as the "Email for order updates" box on a checkout.

Why autocomplete="off" is ignored on passwords

The HTML standard says off asks the browser not to remember or prefill a field. For login fields, most modern browsers ignore it, as MDN notes. A site that blocks the password manager makes users pick short passwords they can remember, and that is a bigger risk than a saved one.

So stop fighting the password manager. Tell it what each field is:

  • An admin page that sets a password for someone else. Use autocomplete="new-password". The manager then suggests a fresh password instead of filling the admin's own.
  • A captcha, a coupon or a search box with your own suggestions. off is fine; these are not credentials.
  • A PIN for a payment step. Use one-time-code if it is a code sent to the user, otherwise off.

Helping password managers

Password managers read the page structure as well as the tokens. Follow these habits:

  1. Use a real <form> with a submit button. One form per task: never merge login and sign-up.
  2. Keep the username in every password form. In a two-step "email first" login, put the email into the password step as a hidden field, as the Chromium password form guide recommends.
  3. Give change-password forms three fields: a hidden username, current-password and new-password.
  4. Navigate after success (or change the URL with the History API), so the manager knows the login worked and offers to save.
  5. Keep name and id stable. Do not rebuild fields on every keystroke.
  6. Publish /.well-known/change-password. This W3C-defined address should redirect to your change-password page. Password managers use it to send users straight there when a password is weak or leaked.

Here is a change-password form that follows all of them:

HTML
<form action="/account/password" method="post">
  <input type="email" name="username" autocomplete="username" value="farhan@example.com" hidden>
  <label for="current">Current password</label>
  <input id="current" name="current" type="password" autocomplete="current-password" required>
  <label for="new">New password</label>
  <input id="new" name="new" type="password" autocomplete="new-password" required>
  <button>Change password</button>
</form>

The Credential Management API

For single-page apps that log in with fetch() and never navigate, the Credential Management API lets script talk to the password manager. Its object is navigator.credentials.

JavaScript
// After a successful fetch() login, ask the browser to save the details
if ("PasswordCredential" in window) {
  const credential = new PasswordCredential(form);  // reads fields by their autocomplete tokens
  await navigator.credentials.store(credential);
}

// On sign-out, stop the browser signing the user in again automatically
await navigator.credentials.preventSilentAccess();

Check the status before you depend on it. Using MDN's compatibility data (November 2026):

PartSupport
navigator.credentials with get() and store()All major browsers
preventSilentAccess()Chrome 60+, Firefox 60+, Safari 17+
PasswordCredentialChrome and Edge only; marked experimental
FederatedCredentialChrome and Edge only; MDN marks it deprecated
PublicKeyCredential (passkeys)All major browsers

So treat PasswordCredential as a bonus for Chromium users. The plain form with correct tokens still does the main job everywhere.

Indian address and PIN code fields

Indian addresses rarely fit Western forms: flat numbers, building names, areas and landmarks matter. Map them like this:

Field labelTokenNotes
Full nameshipping nameOne box; many Indian names have no "last name"
Mobile numbershipping tel-nationalShow "+91" as text beside the box
Flat, house no., buildingshipping address-line1
Area, street, sector, villageshipping address-line2
Landmarkshipping address-line3Optional, like "Near Hanuman Mandir"
PIN codeshipping postal-codeinputmode="numeric", pattern="[1-9][0-9]{5}", maxlength="6"
Town or cityshipping address-level2
Stateshipping address-level1A <select> of states and union territories
Countryshipping country<select> with the value IN

A PIN code has six digits and never starts with 0. Card fields use cc-name, cc-number, cc-exp and cc-csc with inputmode="numeric", but most Indian shops send users to a payment gateway's own page for those, so you rarely write them yourself.

Step 2: audit a form for missing tokens

Reviewing a long form by eye is slow. The script below checks every text-like field: it reports missing values, values the browser rejects, off on credential fields, and passwords without current-password or new-password. It also suggests a token from the label. The sample form for a Lucknow sweet shop has deliberate mistakes.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Autocomplete audit</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    form { display: grid; gap: 4px; max-inline-size: 22rem; }
    table { border-collapse: collapse; margin-block-start: 12px; }
    th, td { border: 1px solid #94a3b8; padding: 4px 8px; text-align: start; }
  </style>
</head>
<body>
  <h1>Lucknow Sweets: delivery details</h1>
  <form>
    <label for="f1">Full name</label> <input id="f1" name="fullname" autocomplete="name">
    <label for="f2">Mobile number</label> <input id="f2" name="mobile" type="tel">
    <label for="f3">Flat, house no., building</label> <input id="f3" name="line1" autocomplete="address-line1">
    <label for="f4">PIN code</label> <input id="f4" name="pin" autocomplete="pincode">
    <label for="f5">Town or city</label> <input id="f5" name="city">
    <label for="f6">State</label> <select id="f6" name="state" autocomplete="address-level1"><option>Uttar Pradesh</option></select>
    <label for="f7">Email for order updates</label> <input id="f7" name="email" type="email">
    <label for="f8">Password</label> <input id="f8" name="pw" type="password" autocomplete="off">
  </form>

  <h2>Audit result</h2>
  <p id="summary"></p>
  <table><thead><tr><th>Field</th><th>Problem</th><th>Suggested</th></tr></thead><tbody id="rows"></tbody></table>

  <script>
    const guesses = [
      [/e-?mail/i, "email"], [/user/i, "username"], [/password/i, "current-password or new-password"],
      [/otp|code sent/i, "one-time-code"], [/mobile|phone/i, "tel-national"], [/pin|postal/i, "postal-code"],
      [/city|town/i, "address-level2"], [/state/i, "address-level1"], [/flat|house|building/i, "address-line1"],
      [/area|street/i, "address-line2"], [/name/i, "name"],
    ];
    const skip = ["hidden", "submit", "button", "reset", "checkbox", "radio", "file", "range", "color", "image"];

    function audit(root) {
      const found = [];
      for (const field of root.querySelectorAll("input, select, textarea")) {
        if (skip.includes(field.type)) continue;
        const label = field.labels[0]?.textContent.trim() || field.name || field.id;
        const raw = field.getAttribute("autocomplete");
        const value = field.autocomplete;                 // "" when missing or invalid
        const isPassword = field.type === "password";
        let problem = "";
        if (raw === null) problem = "No autocomplete attribute";
        else if (value === "") problem = `Invalid value "${raw}"`;
        else if (isPassword && value === "off") problem = "off is ignored on passwords; say what it is";
        else if (isPassword && !/password|one-time-code/.test(value)) problem = "Password needs current-password or new-password";
        if (problem) {
          const guess = guesses.find(([pattern]) => pattern.test(label));
          found.push({ label, problem, suggestion: guess ? guess[1] : "check by hand" });
        }
      }
      return found;
    }

    const results = audit(document.querySelector("form"));
    for (const r of results) {
      const tr = document.createElement("tr");
      for (const text of [r.label, r.problem, r.suggestion]) {
        const td = document.createElement("td");
        td.textContent = text;
        tr.append(td);
      }
      document.querySelector("#rows").append(tr);
    }
    const total = document.querySelectorAll("form input, form select").length;
    document.querySelector("#summary").textContent = `${results.length} of ${total} fields need attention.`;
    console.table(results);
  </script>
</body>
</html>

You should see "5 of 8 fields need attention": the mobile number, PIN code (invalid pincode), city, email and the password with off. Fix them in the HTML and run again until the table is empty. To audit any live page, paste the guesses, skip and audit code into the DevTools Console and run console.table(audit(document)).

Common mistakes

  • autocomplete="off" on login fields. Browsers ignore it, and users suffer.
  • Made-up tokens such as pincode, mobile or fullname. The browser silently treats them as missing.
  • email on a login form. Use username.
  • Prefixes in the wrong order, such as webauthn username or postal-code shipping.
  • A reset page with no username field. The password manager cannot tell which entry to update.
  • One set of address fields for two different addresses. Use shipping, billing or section-*.

Interview questions

1. What is the order of tokens in an autocomplete value?

An optional section-* token, then optionally shipping or billing, then the field name (contact fields may have a home, work, mobile, fax or pager prefix), then optionally webauthn. on and off must appear alone.

2. Why do browsers ignore autocomplete="off" on password fields?

Blocking password managers pushes users towards short, reused passwords, which is worse for security. So browsers keep offering to save and fill credentials. Use the correct tokens instead, such as new-password for an admin setting someone else's password.

3. How can you check in script whether an autocomplete value is valid?

Read the element's autocomplete property. It returns the normalised token list when valid and an empty string when the value is invalid or missing. Use getAttribute() to tell missing from invalid.

4. How do you help a password manager on a password reset page?

Include the account's username in a hidden field with autocomplete="username", and mark the new password with autocomplete="new-password". The manager can then update the right saved entry.

5. Which tokens would you use for an Indian delivery address?

name, tel-national, address-line1 to address-line3, postal-code for the PIN, address-level2 for the city, address-level1 for the state and country, each prefixed with shipping. The PIN field also gets inputmode="numeric" and a six-digit pattern.

Key points

  • autocomplete tokens follow a fixed order: section, shipping or billing, field (with optional contact prefix), then webauthn.
  • The element's autocomplete property returns "" for invalid values, so the browser can check your markup for you.
  • Use username, current-password, new-password, one-time-code and webauthn exactly where they belong.
  • off is ignored on credentials; describe the field instead.
  • Keep a username field, even hidden, on every password form, and publish /.well-known/change-password.
  • PasswordCredential is Chromium-only; correct tokens work everywhere.
  • Map Indian addresses to address-line1-3, address-level2, address-level1 and postal-code.

Exercise

Ananya is sending a Diwali gift from Pune to her grandmother in Jaipur. Build the checkout form: her own contact details (name, mobile, email), a delivery address for the gift (grandmother's name, mobile, address lines, PIN, city, state) and a billing address for her card. Every field needs a correct autocomplete value, with shipping and billing keeping the two addresses apart. Then run the audit script from Step 2 on your form and confirm it reports nothing.

Show solution
HTML
<form action="/checkout" method="post">
  <fieldset>
    <legend>Your details</legend>
    <label for="c-name">Name</label> <input id="c-name" autocomplete="name">
    <label for="c-tel">Mobile (+91)</label> <input id="c-tel" type="tel" autocomplete="tel-national">
    <label for="c-email">Email for updates</label> <input id="c-email" type="email" autocomplete="email">
  </fieldset>
  <fieldset>
    <legend>Gift delivery address</legend>
    <label for="s-name">Recipient's name</label> <input id="s-name" autocomplete="shipping name">
    <label for="s-tel">Recipient's mobile (+91)</label> <input id="s-tel" type="tel" autocomplete="shipping tel-national">
    <label for="s-l1">Flat, house no., building</label> <input id="s-l1" autocomplete="shipping address-line1">
    <label for="s-l2">Area, street</label> <input id="s-l2" autocomplete="shipping address-line2">
    <label for="s-pin">PIN code</label>
    <input id="s-pin" autocomplete="shipping postal-code" inputmode="numeric" pattern="[1-9][0-9]{5}" maxlength="6">
    <label for="s-city">Town or city</label> <input id="s-city" autocomplete="shipping address-level2">
    <label for="s-state">State</label>
    <select id="s-state" autocomplete="shipping address-level1"><option>Rajasthan</option><option>Maharashtra</option></select>
  </fieldset>
  <fieldset>
    <legend>Billing address</legend>
    <label for="b-l1">Flat, house no., building</label> <input id="b-l1" autocomplete="billing address-line1">
    <label for="b-l2">Area, street</label> <input id="b-l2" autocomplete="billing address-line2">
    <label for="b-pin">PIN code</label>
    <input id="b-pin" autocomplete="billing postal-code" inputmode="numeric" pattern="[1-9][0-9]{5}" maxlength="6">
    <label for="b-city">Town or city</label> <input id="b-city" autocomplete="billing address-level2">
  </fieldset>
  <button>Continue to payment</button>
</form>

The contact details have no address-type prefix because they belong to Ananya, not to an address. Pasting this form into the audit page and running audit(document) returns an empty list.

Quick Quiz

1. Which autocomplete value is valid?

2. What does input.autocomplete return when the attribute holds an invalid value?

3. An admin form sets a password for a new staff member. Which value stops the browser filling the admin's own password?

4. Which token should an Indian PIN code field use?

Learn HTML with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call