"use client";
// src/components/PasswordInput/PasswordInput.tsx
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { useId, useState } from "react";
export type PasswordRule = {
/** Text shown in the checklist */
label: string;
/** Returns true when the password passes this rule */
test: (password: string) => boolean;
};
type PasswordInputProps = {
/** Controlled value. Leave out to let the component keep its own value */
value?: string;
onChange?: (value: string) => void;
/** Runs on every change with the score 0-4 and whether every rule passes */
onStrengthChange?: (score: number, allRulesPass: boolean) => void;
/** Field label */
label?: string;
placeholder?: string;
/** Checklist rules - use your own or the default ones */
rules?: PasswordRule[];
/** Show the checklist under the bar */
showChecklist?: boolean;
/** Show the strength word (Weak, Fair, Good, Strong) */
showStrengthText?: boolean;
/** Focus color */
color?: string;
name?: string;
/** "new-password" for sign up, "current-password" for login */
autoComplete?: "new-password" | "current-password";
disabled?: boolean;
className?: string;
};
export const DEFAULT_RULES: PasswordRule[] = [
{ label: "At least 8 characters", test: (p) => p.length >= 8 },
{ label: "One uppercase letter", test: (p) => /[A-Z]/.test(p) },
{ label: "One number", test: (p) => /\d/.test(p) },
{ label: "One special character", test: (p) => /[^A-Za-z0-9]/.test(p) },
];
const LEVELS = [
{ text: "Too short", color: "#A3A3A3" },
{ text: "Weak", color: "#EF4444" },
{ text: "Fair", color: "#F59E0B" },
{ text: "Good", color: "#84CC16" },
{ text: "Strong", color: "#16A34A" },
];
// Very common passwords and patterns are always weak, whatever the rules say
const COMMON = /^(password|qwerty|letmein|welcome|admin|iloveyou|abc123|123456|111111)/i;
/** Score from 0 to 4 based on length, character types, and simple patterns */
export function scorePassword(p: string) {
if (!p) return 0;
let points = 0;
if (p.length >= 8) points++;
if (p.length >= 12) points++;
if (p.length >= 16) points++;
const types = [/[a-z]/, /[A-Z]/, /\d/, /[^A-Za-z0-9]/].filter((r) => r.test(p)).length;
points += types - 1;
// Same character 3+ times in a row, or a simple run like "abc" / "123"
if (/(.)\1\1/.test(p)) points--;
if (/(abc|bcd|cde|123|234|345|456|567|678|789)/i.test(p)) points--;
if (COMMON.test(p)) return 1;
if (p.length < 6) return 1;
return Math.max(1, Math.min(4, Math.round(points * 0.8)));
}
function EyeIcon({ open, reduce }: { open: boolean; reduce: boolean | null }) {
return (
<svg viewBox="0 0 24 24" className="size-5" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7S2 12 2 12z" />
<circle cx={12} cy={12} r={3} />
{/* Slash draws in when the password is hidden */}
<motion.path
d="M4 4l16 16"
initial={false}
animate={{ pathLength: open ? 0 : 1, opacity: open ? 0 : 1 }}
transition={{ duration: reduce ? 0 : 0.25, ease: "easeOut" }}
/>
</svg>
);
}
export function PasswordInput({
value,
onChange,
onStrengthChange,
label = "Password",
placeholder = "Create a password",
rules = DEFAULT_RULES,
showChecklist = true,
showStrengthText = true,
color = "#4F46E5",
name = "password",
autoComplete = "new-password",
disabled = false,
className = "",
}: PasswordInputProps) {
const reduce = useReducedMotion();
const inputId = useId();
const helpId = useId();
const [inner, setInner] = useState("");
const [visible, setVisible] = useState(false);
const [focused, setFocused] = useState(false);
const val = value ?? inner;
const score = scorePassword(val);
const level = LEVELS[score];
const results = rules.map((r) => r.test(val));
const allPass = results.every(Boolean);
const handleChange = (next: string) => {
if (value === undefined) setInner(next);
onChange?.(next);
onStrengthChange?.(scorePassword(next), rules.every((r) => r.test(next)));
};
return (
<div className={`w-full max-w-sm ${className}`}>
<label htmlFor={inputId} className="mb-1.5 block text-sm font-medium text-neutral-800 dark:text-neutral-200">
{label}
</label>
{/* Field */}
<div
className={`flex items-center rounded-xl border-2 bg-white transition-[border-color,box-shadow] duration-200 dark:bg-neutral-900 ${disabled ? "opacity-50" : ""}`}
style={{
borderColor: focused ? color : "rgb(163 163 163 / 0.4)",
boxShadow: focused ? `0 0 0 4px color-mix(in srgb, ${color} 15%, transparent)` : "none",
}}
>
<input
id={inputId}
name={name}
type={visible ? "text" : "password"}
value={val}
onChange={(e) => handleChange(e.target.value)}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
placeholder={placeholder}
autoComplete={autoComplete}
autoCapitalize="off"
autoCorrect="off"
spellCheck={false}
disabled={disabled}
aria-describedby={helpId}
className="h-12 min-w-0 flex-1 rounded-xl bg-transparent pr-2 pl-4 text-base text-neutral-900 outline-none placeholder:text-neutral-400 disabled:cursor-not-allowed dark:text-white"
/>
<button
type="button"
onClick={() => setVisible((v) => !v)}
disabled={disabled}
aria-label={visible ? "Hide password" : "Show password"}
aria-pressed={visible}
aria-controls={inputId}
className="mr-1.5 grid size-9 shrink-0 place-items-center rounded-lg text-neutral-500 transition-colors hover:bg-neutral-100 hover:text-neutral-800 focus-visible:outline-2 dark:hover:bg-neutral-800 dark:hover:text-neutral-100"
style={{ outlineColor: color }}
>
<EyeIcon open={visible} reduce={reduce} />
</button>
</div>
{/* Strength bar: 4 segments that fill with the level color */}
<div className="mt-3 flex items-center gap-3" aria-hidden="true">
<div className="grid flex-1 grid-cols-4 gap-1.5">
{[1, 2, 3, 4].map((seg) => (
<div key={seg} className="h-1.5 overflow-hidden rounded-full bg-neutral-200 dark:bg-neutral-800">
<motion.div
className="h-full rounded-full"
initial={false}
animate={{
scaleX: val && score >= seg ? 1 : 0,
backgroundColor: level.color,
}}
style={{ originX: 0 }}
transition={
reduce
? { duration: 0 }
: {
scaleX: { type: "spring", stiffness: 300, damping: 30, delay: (seg - 1) * 0.04 },
backgroundColor: { duration: 0.25 },
}
}
/>
</div>
))}
</div>
{/* Strength word slides up when it changes */}
{showStrengthText && (
<div className="relative h-5 w-16 overflow-hidden text-right text-xs font-semibold">
<AnimatePresence mode="popLayout" initial={false}>
{val && (
<motion.span
key={level.text}
className="absolute inset-0"
style={{ color: level.color }}
initial={reduce ? { opacity: 0 } : { y: 14, opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
exit={reduce ? { opacity: 0 } : { y: -14, opacity: 0 }}
transition={{ duration: 0.2 }}
>
{level.text}
</motion.span>
)}
</AnimatePresence>
</div>
)}
</div>
{/* Checklist */}
{showChecklist && (
<ul id={helpId} className="mt-3 space-y-1.5">
{rules.map((rule, i) => {
const ok = results[i];
return (
<li key={rule.label} className="flex items-center gap-2 text-sm">
<motion.span
className="grid size-4.5 shrink-0 place-items-center rounded-full"
initial={false}
animate={{
backgroundColor: ok ? "#16A34A" : "rgba(163,163,163,0.25)",
scale: ok && !reduce ? [1, 1.25, 1] : 1,
}}
transition={{ duration: reduce ? 0 : 0.3 }}
aria-hidden="true"
>
<svg viewBox="0 0 24 24" className="size-3 text-white" fill="none" stroke="currentColor" strokeWidth={3.5} strokeLinecap="round" strokeLinejoin="round">
<motion.path
d="M5 12.5l4.5 4.5L19 7.5"
initial={false}
animate={{ pathLength: ok ? 1 : 0, opacity: ok ? 1 : 0 }}
transition={{ duration: reduce ? 0 : 0.25, ease: "easeOut" }}
/>
</svg>
</motion.span>
<span className={`transition-colors duration-200 ${ok ? "text-neutral-800 dark:text-neutral-200" : "text-neutral-500 dark:text-neutral-400"}`}>
{rule.label}
<span className="sr-only">{ok ? " - done" : " - not done yet"}</span>
</span>
</li>
);
})}
</ul>
)}
{!showChecklist && <span id={helpId} className="sr-only">{rules.map((r) => r.label).join(", ")}</span>}
{/* Tells screen readers the strength, without reading every keystroke */}
<span className="sr-only" role="status" aria-live="polite">
{val ? `Password strength: ${level.text}${allPass ? ". All requirements met" : ""}` : ""}
</span>
</div>
);
}
export default PasswordInput;
// Component Source: https://codekk.deComponent details
Overview, install command, dependencies, and project links.
An animated password strength input for React built with TypeScript, Motion, and Tailwind CSS v4. It's made for sign up forms, reset password pages, account settings, and admin panels. As you type, a 4-step strength meter fills from left to right with a soft spring, and its color moves from red to amber to lime to green. The strength word next to it (Weak, Fair, Good, Strong) slides up each time it changes. Under the meter, a checklist shows the password rules. When a rule passes, its circle turns green with a small pop and a check mark draws itself in. The eye button shows or hides the password, and a slash line draws across the eye when the password is hidden. The strength score is smarter than just counting rules: it looks at length, the mix of lowercase, uppercase, numbers, and symbols, and it lowers the score for repeated characters like "aaa", simple runs like "abc" or "123", and very common passwords like "password". The rules are fully custom: pass your own list with a label and a test function, for example a minimum length, no spaces, or not containing the user's name. onStrengthChange gives you the score and whether every rule passes, so you can turn the submit button on only when the password is ready. The scorePassword function and the default rules are also exported, so you can use the same check on your server. It works as a controlled or uncontrolled input, sets autocomplete to "new-password" so browsers can suggest a strong password, and turns off autocorrect and auto capitalize. The focus color can be changed, and dark mode styles are included. Screen readers hear the rules through aria-describedby, each rule says if it's done, and a polite live region announces the strength. When prefers-reduced-motion is enabled, the fills, pops, and slides are turned off and only colors change. "use client" is included, so it works in Vite, Create React App, and Next.js.
Install
npm create vite@latest my-app -- --template react-ts cd my-app npm install motionDependencies
Discussion
Feedback, implementation tips, and usage notes.
Comments
Sign in to join the conversation
Similar Components
More from the same category

