# Password strength

> A new-password field with a four-part meter, a live count and a checklist that explains every filled segment.

- Kind: ui · Category: Forms · Interactivity: script
- Install: `npx shadcn@latest add @haze/password-strength`
- File: `src/components/haze/ui/password-strength.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/label, @haze/password-input, @haze/utils
- Docs page: https://hazeui.com/ui/password-strength

## Use when
- A signup or password-change form needs to show which character rules are met as the user types.
- A visible count and individual criteria help people revise a proposed password.

## Avoid when
- A returning user is signing in. Use password-input.
- A server needs to detect compromised credentials or enforce a password policy.

## Alternatives
- [password-input](https://hazeui.com/ui/password-input.md)
- [input](https://hazeui.com/ui/input.md)
- [progress](https://hazeui.com/ui/progress.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | ID of the password input and prefix for its rule and error descriptions. |
| name | `string` | id | no | Name submitted by the native password field. |
| label | `string` | New password | no | Visible field label. |
| lengthTarget | `number` | 12 | no | Minimum number of Unicode code points for the length check. The other checks recognize mixed case, a decimal digit and punctuation or a symbol. |
| autocomplete | `string` | new-password | no | Native autofill hint. |
| required / disabled | `boolean` |  | no | Native required and disabled states. |
| error | `string` |  | no | External validation message associated with the input. |
| toggleLabel | `string` | Show password | no | Accessible name of the visibility toggle. |
| class | `string` |  | no | Classes applied to the wrapper. |
| ...attributes | `HTML input attributes` |  | no | Additional native attributes, including form, value and maxlength. Caller descriptions are combined with the checklist. |

## Accessibility
- Each displayed rule has an audible met or pending state. The meter announces changes to the total.
- Without scripting, the labelled password field and its written criteria remain available.
- The segment fills and check marks update immediately when reduced motion is requested.
- Key Enter / Space: Toggle visibility when the reveal button has focus.

## Agent prompts

### Install and use

Install the Haze UI component "Password strength" with `npx shadcn@latest add @haze/password-strength`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import PasswordStrength from "@/components/haze/ui/password-strength.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/password-strength.md

### Customize with real content

Adapt the Haze password-strength ui for our product. Replace the demo values of these props with our real content: id, name, label, lengthTarget, autocomplete, required / disabled, error, toggleLabel, class, ...attributes. Keep the layout, the heading level rules and these accessibility details: Each displayed rule has an audible met or pending state. The meter announces changes to the total. Without scripting, the labelled password field and its written criteria remain available. The segment fills and check marks update immediately when reduced motion is requested. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using password-strength, check it fits: use it when a signup or password-change form needs to show which character rules are met as the user types.; a visible count and individual criteria help people revise a proposed password.. Avoid it when a returning user is signing in. use password-input.; a server needs to detect compromised credentials or enforce a password policy.. Alternatives: @haze/password-input, @haze/input, @haze/progress.

## Example requests that should lead here
- Show a change-password field with four visible character checks and a live count beside the meter.

## Source

```astro
---
import { Check } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Label from "./label.astro";
import PasswordInput from "./password-input.astro";

interface Props {
  id: string;
  name?: string;
  label?: string;
  lengthTarget?: number;
  autocomplete?: string;
  required?: boolean;
  disabled?: boolean;
  error?: string;
  toggleLabel?: string;
  class?: string;
  "aria-describedby"?: string;
  [key: string]: unknown;
}

const { id, name = id, label = "New password", lengthTarget = 12, autocomplete = "new-password", required, disabled,
  error, toggleLabel = "Show password", class: className, "aria-describedby": describedBy, ...rest } = Astro.props;
const minimum = Number.isFinite(lengthTarget) ? Math.max(1, Math.trunc(lengthTarget)) : 12;
const rules = [
  { key: "length", label: `At least ${minimum} ${minimum === 1 ? "character" : "characters"}` },
  { key: "case", label: "Uppercase and lowercase letters" },
  { key: "number", label: "A number" },
  { key: "symbol", label: "A punctuation mark or symbol" },
];
const summaries = ["0 of 4 checks", "1 of 4 checks", "2 of 4 checks", "3 of 4 checks", "All 4 checks met"];
const descriptionIds = [describedBy, `${id}-rules`, error && `${id}-error`].filter(Boolean).join(" ");
---

<div data-haze-password-strength data-length-target={minimum} class={cn("group/strength grid w-full min-w-0 gap-3", className)}>
  <div class="grid min-w-0 gap-1.5">
    <Label for={id} required={required}>{label}</Label>
    <PasswordInput {...rest} id={id} name={name} autocomplete={autocomplete} required={required} disabled={disabled} toggleLabel={toggleLabel}
      aria-invalid={error ? "true" : rest["aria-invalid"]} aria-describedby={descriptionIds} class="pointer-coarse:text-base" />
    {error && <p id={`${id}-error`} class="text-xs/5 wrap-anywhere text-destructive">{error}</p>}
  </div>
  <div data-strength-feedback hidden class="grid gap-2 [&[hidden]]:hidden">
    <div data-strength-meter role="meter" aria-label="Password checks met" aria-valuemin="0" aria-valuemax="4" aria-valuenow="0" class="grid grid-cols-4 gap-1.5">
      {rules.map((_, index) => (
        <span aria-hidden="true" class="relative block h-1.5 overflow-hidden rounded-full bg-input forced-colors:border">
          <span data-strength-segment style={`--fill-delay:${index * 25}ms`}
            class="absolute inset-0 origin-left scale-x-0 rounded-full bg-brand data-filled:scale-x-100 group-data-[level='1']/strength:bg-warning group-data-[level='2']/strength:bg-warning group-data-[level='4']/strength:bg-success motion-safe:transition-[scale,background-color] motion-safe:duration-200 motion-safe:ease-snappy motion-safe:data-filled:delay-(--fill-delay) forced-colors:bg-[Highlight]"></span>
        </span>
      ))}
    </div>
    <div aria-hidden="true" class="grid overflow-hidden text-[0.8125rem]/5 font-medium tabular-nums">
      {summaries.map((summary) => <span data-strength-summary class="col-start-1 row-start-1 -translate-y-1 opacity-0 data-current:translate-y-0 data-current:opacity-100 motion-safe:transition-[opacity,translate] motion-safe:duration-150 motion-safe:ease-snappy">{summary}</span>)}
    </div>
  </div>
  <ul id={`${id}-rules`} role="list" aria-label="Password criteria" class="grid min-w-0 gap-1.5">
    {rules.map(({ key, label: ruleLabel }) => (
      <li data-strength-rule={key} class="group/rule flex min-w-0 items-center gap-2 text-[0.8125rem]/5 text-muted-foreground data-met:text-foreground">
        <span aria-hidden="true" class="relative grid size-4 shrink-0 place-items-center rounded-full border border-border-control group-data-met/rule:border-success group-data-met/rule:bg-success/14">
          <Check class="size-3 text-success opacity-0 [stroke-dasharray:24] [stroke-dashoffset:24] group-data-met/rule:opacity-100 group-data-met/rule:[stroke-dashoffset:0] motion-safe:transition-[stroke-dashoffset,opacity] motion-safe:duration-200 motion-safe:ease-snappy" />
        </span>
        <span class="min-w-0 wrap-anywhere">{ruleLabel}<span data-rule-status class="sr-only"></span></span>
        {key === "length" && <span hidden data-remaining aria-hidden="true" class="ms-auto shrink-0 overflow-hidden font-mono text-xs/5 tabular-nums [&[hidden]]:hidden"></span>}
      </li>
    ))}
  </ul>
  <p role="status" aria-atomic="true" class="sr-only" data-strength-status></p>
</div>

<script>
  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const input = root.querySelector<HTMLInputElement>("input");
    const feedback = root.querySelector<HTMLElement>("[data-strength-feedback]");
    const meter = root.querySelector<HTMLElement>("[data-strength-meter]");
    const status = root.querySelector<HTMLElement>("[data-strength-status]");
    if (!input || !feedback || !meter || !status) return;
    const rows = Array.from(root.querySelectorAll<HTMLElement>("[data-strength-rule]"));
    const segments = Array.from(root.querySelectorAll<HTMLElement>("[data-strength-segment]"));
    const summaries = Array.from(root.querySelectorAll<HTMLElement>("[data-strength-summary]"));
    const remaining = root.querySelector<HTMLElement>("[data-remaining]");
    const minimum = Number(root.dataset.lengthTarget);
    let previous = -1;

    const sync = () => {
      const value = input.value;
      const length = [...value].length;
      const checks: Record<string, boolean> = {
        length: length >= minimum,
        case: /\p{Lu}/u.test(value) && /\p{Ll}/u.test(value),
        number: /\p{Nd}/u.test(value),
        symbol: /[\p{P}\p{S}]/u.test(value),
      };
      const level = Object.values(checks).filter(Boolean).length;
      rows.forEach((row) => {
        const met = checks[row.dataset.strengthRule ?? ""] ?? false;
        if (row.hasAttribute("data-met") !== met || !row.hasAttribute("data-scored")) {
          row.toggleAttribute("data-met", met);
          row.setAttribute("data-scored", "");
          const ruleStatus = row.querySelector<HTMLElement>("[data-rule-status]");
          if (ruleStatus) ruleStatus.textContent = met ? ", met" : ", pending";
        }
      });
      if (remaining) {
        remaining.hidden = !length || length >= minimum;
        const next = `${minimum - length} left`;
        if (!remaining.hidden && remaining.textContent !== next) {
          const count = document.createElement("span");
          count.className = previous < 0 ? "inline-block" : "inline-block motion-safe:animate-rise";
          count.textContent = next;
          remaining.replaceChildren(count);
        }
      }
      if (level === previous) return;
      root.dataset.level = String(level);
      segments.forEach((segment, index) => segment.toggleAttribute("data-filled", index < level));
      summaries.forEach((summary, index) => summary.toggleAttribute("data-current", index === level));
      const text = summaries[level].textContent ?? "";
      meter.setAttribute("aria-valuenow", String(level));
      meter.setAttribute("aria-valuetext", text);
      if (previous !== -1) status.textContent = text;
      previous = level;
    };
    input.addEventListener("input", sync);
    input.addEventListener("change", sync);
    input.form?.addEventListener("reset", (event) => queueMicrotask(() => { if (!event.defaultPrevented) sync(); }));
    sync();
    feedback.hidden = false;
    root.setAttribute("data-enhanced", "");
  }
  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-password-strength]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-password-strength-listener")) {
    document.documentElement.setAttribute("data-haze-password-strength-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
