Try 'magnetic button'
View code

Number 88: Sign-up form that waits before it complains

Specification

Catalogue
No. 88 of 110
Interaction
Type, Feedback
Element
Form, Input
Preview
Live component
Imports
react 19.3.1, framer-motion 12.40.0
Added

Notes

A field is flagged only after the visitor leaves it with something in it, or presses Create account, and the message clears the moment the value is fixed. Under the password one line swaps between a hint, the strength and the error, beside a four-step meter.

The timing is what makes a form feel polite, and most sites get it wrong: errors while the visitor is still typing, or only after submit. Here nobody is told off for an address they have not finished, and nobody has to submit twice to find out what is wrong.

Messages swap in place, rising out of a 4px blur over 200ms cubic-bezier(.16, 1, .3, 1), and every message row keeps its height, so nothing below moves. Strength counts four things (8 or more characters, 12 or more, mixed case, a number or symbol); each meter step fills in ink. A submit with mistakes moves focus to the first one. Create account becomes its own spinner, then the form crosses over sideways to a welcome whose ring and tick draw themselves, and the card's height glides between the two. Every control is 44px; inputs are 16px with proper autocomplete. Crossfades only under reduced motion.

Sign-up is simulated in the preview.

Code

React and plain CSS
"use client";

import { useEffect, useId, useRef, useState, type FormEvent, type ReactNode } from "react";
import { AnimatePresence, motion } from "framer-motion";
import type { LivePreviewProps } from "@/components/live/types";
import { EASE_ENTER } from "@/components/pieces/kit/physical-spring";
import { useSafeReducedMotion } from "@/components/pieces/kit/use-safe-reduced-motion";
import { AutoHeight } from "@/components/pieces/motion-helpers";
import { PieceStage } from "@/components/pieces/stage/PieceStage";
import type { Tour } from "@/components/pieces/stage/tour";
import "./sign-up-checks.css";

type Field = "name" | "email" | "password";

function errorsFor(v: Record<Field, string>): Record<Field, string> {
  return {
    name: v.name.trim().length < 2 ? "Enter your full name." : "",
    email: !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(v.email.trim()) ? "Enter a full address, like name@example.com." : "",
    password: v.password.length < 8 ? "Use at least 8 characters." : "",
  };
}

/** 0 to 4: long enough, longer still, mixed case, a number or symbol. */
function score(p: string): number {
  if (!p) return 0;
  return [p.length >= 8, p.length >= 12, /[a-z]/.test(p) && /[A-Z]/.test(p), /\d|[^\w\s]/.test(p)].filter(Boolean).length;
}
const STRENGTH = ["", "Weak", "Fair", "Good", "Strong"];

function SignUpDemo() {
  const reduce = useSafeReducedMotion();
  const uid = useId();
  const [v, setV] = useState<Record<Field, string>>({ name: "", email: "", password: "" });
  const [touched, setTouched] = useState<Record<Field, boolean>>({ name: false, email: false, password: false });
  const [submitted, setSubmitted] = useState(false);
  const [busy, setBusy] = useState(false);
  const [done, setDone] = useState(false);
  const refs = { name: useRef<HTMLInputElement>(null), email: useRef<HTMLInputElement>(null), password: useRef<HTMLInputElement>(null) };
  const doneRef = useRef<HTMLHeadingElement>(null);
  const timer = useRef<number | undefined>(undefined);

  useEffect(() => () => window.clearTimeout(timer.current), []);
  useEffect(() => {
    if (done) doneRef.current?.focus({ preventScroll: true });
  }, [done]);

  const errors = errorsFor(v);
  // A field complains only once the visitor has left it with something in it, or pressed submit; it stops the moment it is fixed.
  const shown = (f: Field) => (touched[f] || submitted ? errors[f] : "");
  const s = score(v.password);
  const pwError = shown("password");
  const feedback = pwError ? { k: "err", t: pwError } : v.password ? { k: `s${s}`, t: `${STRENGTH[Math.max(s, 1)]} password` } : { k: "hint", t: "Use 8 or more characters." };

  const submit = (e: FormEvent) => {
    e.preventDefault();
    if (busy) return;
    setSubmitted(true);
    const first = (Object.keys(errors) as Field[]).find((f) => errors[f]);
    if (first) {
      refs[first].current?.focus();
      return;
    }
    setBusy(true);
    // Simulated server. A real build shows the welcome only once the account exists.
    timer.current = window.setTimeout(() => {
      setBusy(false);
      setDone(true);
    }, 700);
  };
  const reset = () => {
    setV({ name: "", email: "", password: "" });
    setTouched({ name: false, email: false, password: false });
    setSubmitted(false);
    setDone(false);
    window.setTimeout(() => refs.name.current?.focus(), 0);
  };

  const input = (f: Field, label: string, type: string, auto: string) => {
    const err = f === "password" ? "" : shown(f);
    return (
      <div className="su-field">
        <label htmlFor={`${uid}-${f}`}>{label}</label>
        <input
          ref={refs[f]}
          id={`${uid}-${f}`}
          className={`su-input su-${f}`}
          type={type}
          autoComplete={auto}
          autoCapitalize={f === "name" ? "words" : "off"}
          spellCheck={false}
          value={v[f]}
          readOnly={busy}
          aria-invalid={(f === "password" ? !!pwError : !!err) || undefined}
          aria-describedby={`${uid}-${f}-m`}
          onChange={(e) => setV((cur) => ({ ...cur, [f]: e.target.value }))}
          onBlur={() => {
            if (v[f]) setTouched((t) => ({ ...t, [f]: true }));
          }}
        />
        {f === "password" ? (
          <div className="su-feedback">
            <span id={`${uid}-${f}-m`} className="su-msg" data-error={!!pwError || undefined} role={pwError ? "alert" : undefined}>
              <Swap k={feedback.k} reduce={reduce}>
                {feedback.t}
              </Swap>
            </span>
            <span className="su-meter" aria-hidden="true">
              {[1, 2, 3, 4].map((b) => (
                <span key={b} data-on={b <= s || undefined} />
              ))}
            </span>
          </div>
        ) : (
          <span id={`${uid}-${f}-m`} className="su-msg" data-error role={err ? "alert" : undefined}>
            <Swap k={err || "none"} reduce={reduce}>
              {err}
            </Swap>
          </span>
        )}
      </div>
    );
  };

  return (
    <div className="su">
      <AutoHeight className="su-card" duration={reduce ? 0 : 320}>
        <AnimatePresence mode="popLayout" initial={false}>
          {!done ? (
            <motion.form
              key="form"
              className="su-form"
              noValidate
              onSubmit={submit}
              aria-labelledby={`${uid}-h`}
              initial={reduce ? { opacity: 0 } : { opacity: 0, x: -24, filter: "blur(4px)" }}
              animate={{ opacity: 1, x: 0, filter: "blur(0px)" }}
              exit={reduce ? { opacity: 0, transition: { duration: 0 } } : { opacity: 0, x: -16, filter: "blur(4px)", transition: { duration: 0.15 } }}
              transition={{ duration: reduce ? 0 : 0.24, ease: EASE_ENTER }}
            >
              <h3 id={`${uid}-h`} className="su-title">
                Create your account
              </h3>
              {input("name", "Full name", "text", "name")}
              {input("email", "Email", "email", "email")}
              {input("password", "Password", "password", "new-password")}
              <button type="submit" className="su-submit" aria-busy={busy || undefined}>
                {busy ? (
                  <>
                    <span className="su-spin" aria-hidden="true" />
                    Creating account
                  </>
                ) : (
                  "Create account"
                )}
              </button>
            </motion.form>
          ) : (
            <motion.div
              key="done"
              className="su-done"
              initial={reduce ? { opacity: 0 } : { opacity: 0, x: 24, filter: "blur(4px)" }}
              animate={{ opacity: 1, x: 0, filter: "blur(0px)" }}
              transition={{ duration: reduce ? 0 : 0.28, ease: EASE_ENTER, delay: reduce ? 0 : 0.05 }}
            >
              <svg className="su-tick" viewBox="0 0 48 48" aria-hidden="true">
                <motion.circle cx="24" cy="24" r="22" fill="none" stroke="currentColor" strokeWidth="1.5" initial={reduce ? false : { pathLength: 0 }} animate={{ pathLength: 1 }} transition={{ duration: 0.5, ease: "easeInOut", delay: 0.16 }} />
                <motion.path d="M15.5 24.5l5.5 5.5 11.5-12" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" initial={reduce ? false : { pathLength: 0 }} animate={{ pathLength: 1 }} transition={{ duration: 0.28, ease: EASE_ENTER, delay: 0.5 }} />
              </svg>
              <h3 ref={doneRef} tabIndex={-1} className="su-title">
                Welcome, {v.name.trim().split(/\s+/)[0]}
              </h3>
              <p className="su-sent">
                Your account is ready. A confirmation went to <strong>{v.email.trim()}</strong>.
              </p>
              <button type="button" className="su-again" onClick={reset}>
                Start over
              </button>
            </motion.div>
          )}
        </AnimatePresence>
      </AutoHeight>
      <p className="su-note">Sign-up is simulated in this preview.</p>
    </div>
  );
}

/** A message that swaps in place: the old one lifts away, the new one settles out of a small blur. */
function Swap({ k, reduce, children }: { k: string; reduce: boolean; children: ReactNode }) {
  return (
    <AnimatePresence mode="popLayout" initial={false}>
      <motion.span
        key={k}
        className="su-swap"
        initial={reduce ? { opacity: 0 } : { opacity: 0, y: -4, filter: "blur(4px)" }}
        animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
        exit={reduce ? { opacity: 0, transition: { duration: 0 } } : { opacity: 0, y: -4, filter: "blur(4px)", transition: { duration: 0.12 } }}
        transition={{ duration: reduce ? 0 : 0.2, ease: EASE_ENTER }}
      >
        {children}
      </motion.span>
    </AnimatePresence>
  );
}

// What a hovered card shows: a mistyped address flagged on submit, fixed, a password that grows stronger, and the welcome.
const TOUR: Tour = [
  { input: ".su-name", value: "Ana Sousa", wait: 500 },
  { input: ".su-email", value: "ana@studio", wait: 500 },
  { click: ".su-submit", wait: 1100 },
  { input: ".su-email", value: "ana@studio.pt", wait: 800 },
  { input: ".su-password", value: "kiln", wait: 600 },
  { input: ".su-password", value: "Kiln-41-glaze", wait: 900 },
  { click: ".su-submit", wait: 2000 },
];

export default function SignUpChecksEntry(props: LivePreviewProps) {
  return (
    <PieceStage {...props} label="Sign-up form that waits before it complains" tour={TOUR}>
      <SignUpDemo />
    </PieceStage>
  );
}

More like this

Form in named steps

Type, FeedbackForms and inputs

Code field that behaves as one input

Type, FeedbackForms and inputs

Sign-up that hands over the next issue

Type, FeedbackForms and inputs

Cookie choice that folds away

FeedbackOverlays and toasts

Search clear that dissolves word by word

Type, FeedbackForms and inputs

Estimate slider

Drag, TypeForms and inputs