Password Input
Password field with a show and hide toggle at the end and an optional four step strength meter with a word. Supports controlled and uncontrolled value.
How it differs. Baseline masked field with a single visibility toggle inside the field and an opt-in strength meter under it, with no rule checklist.
Install
pnpm dlx shadcn@latest add @hazine/password-inputAdds 1 file, 1 shadcn primitive (input), 1 Hazine item (@hazine/use-controllable-state), 1 package (lucide-react), and the success and warning tokens.
First time? Add the registry to components.json
{
"registries": {
"@hazine": "https://api.hazine.dev/r/{name}.json"
}
}Needed once per project. Items resolve each other through the @hazine namespace.
components/hazine/password-input.tsx, 132 lines
"use client"
import * as React from "react"
import { Eye, EyeOff } from "lucide-react"
import { cn } from "@/lib/utils"
import { Input } from "@/components/ui/input"
import { useControllableState } from "@/hooks/use-controllable-state"
const STRENGTH_LABELS = ["Too weak", "Weak", "Fair", "Good", "Strong"]
const STRENGTH_FILLS = [
"bg-destructive",
"bg-destructive",
"bg-warning",
"bg-success",
"bg-success",
]
const TOGGLE_CLASS =
"absolute inset-y-0 end-0 flex w-9 items-center justify-center rounded-e-md text-muted-foreground transition-colors duration-100 hover:text-foreground focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-foreground disabled:pointer-events-none disabled:opacity-50"
function scorePassword(value: string) {
let score = 0
if (value.length >= 8) score++
if (value.length >= 12) score++
if (/[A-Z]/.test(value) && /[a-z]/.test(value)) score++
if (/\d/.test(value)) score++
if (/[^A-Za-z0-9]/.test(value)) score++
return Math.min(score, 4)
}
/** Props are spread on the input, not on the root. */
export interface PasswordInputProps
extends Omit<
React.ComponentProps<typeof Input>,
"type" | "value" | "defaultValue"
> {
value?: string
defaultValue?: string
onValueChange?: (value: string) => void
/** Shows a four step strength meter with a word under the field. */
showStrength?: boolean
/** Accessible name of the visibility toggle. It does not change when pressed. */
toggleLabel?: string
/** Text before the strength word, for example "Password strength". */
strengthLabel?: string
}
export function PasswordInput({
value,
defaultValue = "",
onValueChange,
showStrength = false,
toggleLabel = "Show password",
strengthLabel = "Password strength",
id,
disabled,
className,
onChange,
"aria-describedby": describedBy,
...props
}: PasswordInputProps) {
const generatedId = React.useId()
const inputId = id ?? generatedId
const strengthId = `${inputId}-strength`
const [visible, setVisible] = React.useState(false)
const [current, setCurrent] = useControllableState({
value,
defaultValue,
onChange: onValueChange,
})
const score = scorePassword(current)
const describedByIds = [describedBy, showStrength ? strengthId : null]
.filter(Boolean)
.join(" ")
return (
<div data-slot="password-input" className="flex w-full flex-col gap-2">
<div className="relative">
<Input
id={inputId}
type={visible ? "text" : "password"}
value={current}
disabled={disabled}
aria-describedby={describedByIds || undefined}
className={cn("pe-9", className)}
onChange={(event) => {
setCurrent(event.target.value)
onChange?.(event)
}}
{...props}
/>
<button
type="button"
data-slot="password-input-toggle"
aria-label={toggleLabel}
aria-pressed={visible}
aria-controls={inputId}
disabled={disabled}
className={TOGGLE_CLASS}
onClick={() => setVisible((previous) => !previous)}
>
{visible ? (
<EyeOff aria-hidden="true" className="size-4" />
) : (
<Eye aria-hidden="true" className="size-4" />
)}
</button>
</div>
{showStrength && (
<div data-slot="password-input-strength" className="flex flex-col gap-1.5">
<div aria-hidden="true" className="flex gap-1">
{[0, 1, 2, 3].map((step) => (
<span
key={step}
className={cn(
"h-1.5 flex-1 rounded-full bg-muted transition-colors duration-150",
current.length > 0 && step < score && STRENGTH_FILLS[score]
)}
/>
))}
</div>
<p id={strengthId} role="status" className="text-xs text-muted-foreground">
{strengthLabel}:{" "}
<span className="font-medium text-foreground">
{current.length > 0 ? STRENGTH_LABELS[score] : "Not set"}
</span>
</p>
</div>
)}
</div>
)
}
The demo in the preview, 80 lines
import * as React from "react"
import { CircleAlert } from "lucide-react"
import { Label } from "@/components/ui/label"
import { PasswordInput } from "@/components/hazine/password-input"
export default function PasswordInputDemo() {
const id = React.useId()
return (
<div className="grid gap-2">
<Label htmlFor={id}>New password</Label>
<PasswordInput id={id} autoComplete="new-password" showStrength />
</div>
)
}
function PasswordInputPlain() {
const id = React.useId()
return (
<div className="grid gap-2">
<Label htmlFor={id}>Password</Label>
<PasswordInput id={id} autoComplete="current-password" />
</div>
)
}
function PasswordInputInvalid() {
const id = React.useId()
const errorId = React.useId()
return (
<div className="grid gap-2">
<Label htmlFor={id}>Password</Label>
<PasswordInput
id={id}
autoComplete="current-password"
defaultValue="harbour"
aria-invalid="true"
aria-describedby={errorId}
/>
<p
id={errorId}
className="flex items-center gap-1.5 text-sm text-destructive"
>
<CircleAlert aria-hidden="true" className="size-3.5 shrink-0" />
That password does not match this account. Try again or reset it.
</p>
</div>
)
}
function PasswordInputDisabled() {
const id = React.useId()
return (
<div className="grid gap-2">
<Label htmlFor={id}>Password</Label>
<PasswordInput id={id} defaultValue="harbour-light-42" disabled />
<p className="text-xs text-muted-foreground">
Your workspace signs in through single sign-on, so the password is
managed by your identity provider.
</p>
</div>
)
}
function PasswordInputReadOnly() {
const id = React.useId()
return (
<div className="grid gap-2">
<Label htmlFor={id}>Generated password</Label>
<PasswordInput id={id} defaultValue="Larch-Quay-7418-mist" readOnly />
</div>
)
}
export const scenarios = {
plain: PasswordInputPlain,
invalid: PasswordInputInvalid,
disabled: PasswordInputDisabled,
"read-only": PasswordInputReadOnly,
}
Props6
- value
- string
- defaultValue
- string = ""
- onValueChange
- (value: string) => void
- showStrength
- boolean = false
- Shows a four step strength meter with a word under the field.
- toggleLabel
- string = "Show password"
- Accessible name of the visibility toggle. It does not change when pressed.
- strengthLabel
- string = "Password strength"
- Text before the strength word, for example "Password strength".
Also accepts every prop of Omit< React.ComponentProps<typeof Input>, "type" | "value" | "defaultValue" >.
Accessibility
- Pattern
- Form with labelled fields, Button (APG, opens in a new tab)
- Keyboard
Keyboard support for Password Input Key Effect Tab Moves from the field to the visibility toggle Enter or Space on the toggle Shows or hides the password and keeps focus on the toggle - Screen reader
A native input the consumer labels. The toggle is a button with aria-pressed and aria-controls, and the strength word sits in a status region linked by aria-describedby.
- Announces: Password strength: {word}
- Reduced motion
- No motion. Colour transitions only.
- Checked
- Not checked yet. Automated results appear here once CI has run.
Dependencies3
- input
- @hazine/use-controllable-state
- lucide-react
Filled chips are registry items the CLI adds for you. Outlined chips are npm packages.
Tokens shipped4
- --success
- --success-foreground
- --warning
- --warning-foreground
Added to your stylesheet in light and dark, unless you already define them.