Skip to content

Forms

Pulze forms use react-hook-form for state and zod for validation (both MIT). The pieces:

Block What it is
Field Label + control + hint + error, with the accessibility attributes wired up
FormField Field connected to react-hook-form
FormSection A settings row: title and explanation on the left, fields on the right
SaveBar "You have unsaved changes · Cancel · Save", appears when the form changes
PasswordInput Show/hide, optional strength meter and rules
OtpInput One-time code boxes: auto-advance, paste, Backspace
Segmented A small set of exclusive options with a sliding highlight

Inputs, selects, checkboxes, radios, switches and text areas are the shadcn primitives in @pulze/ui/components/*, styled to match Pulze.

1. A complete form

import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod"

const schema = z.object({
  name: z.string().min(2, "Enter at least 2 characters."),
  email: z.email("Enter a full email address, like name@company.com."),
  role: z.enum(["admin", "editor", "viewer"]),
})
type Values = z.infer<typeof schema>

export function ProfileForm({ user }: { user: Values }) {
  const form = useForm<Values>({
    resolver: zodResolver(schema),
    defaultValues: user,
    mode: "onTouched",
  })
  const save = form.handleSubmit(async (values) => {
    await updateUser(values)
    form.reset(values) // the form is "clean" again, so the save bar hides
    toast.success("Profile saved")
  })

  return (
    <form onSubmit={save} noValidate className="rounded-xl border bg-card">
      <FormSection
        title="Personal info"
        description="Your name and how people reach you."
      >
        <FormField control={form.control} name="name" label="Full name" required>
          {(field, a11y) => <Input {...field} {...a11y} autoComplete="name" />}
        </FormField>
        <FormField control={form.control} name="email" label="Email" required>
          {(field, a11y) => (
            <Input {...field} {...a11y} type="email" autoComplete="email" />
          )}
        </FormField>
      </FormSection>
      <SaveBar
        dirty={form.formState.isDirty}
        saving={form.formState.isSubmitting}
        onCancel={() => form.reset()}
      />
    </form>
  )
}

What you get:

  • Errors in plain words. Each error shows under its field, in the words you wrote in the schema.
  • Accessible fields. Each field gets aria-invalid and aria-describedby, so screen readers announce the error.
  • The save bar slides up as soon as something changes, and disappears after saving or cancelling.

2. Writing good error messages

Say what to do, not what went wrong:

  • "Enter a full email address, like name@company.com", not "Invalid email".
  • "Use 12 or more characters", not "Password too short".

3. Each control with FormField

// Select
<FormField control={form.control} name="role" label="Role">
  {(field, a11y) => (
    <Select items={ROLES} value={field.value} onValueChange={field.onChange}>
      <SelectTrigger id={a11y.id} className="w-full"><SelectValue /></SelectTrigger>
      <SelectContent>{ROLES.map((r) => <SelectItem key={r.value} value={r.value}>{r.label}</SelectItem>)}</SelectContent>
    </Select>
  )}
</FormField>

// Switch
<FormField control={form.control} name="updates" label="Email me product updates">
  {(field, a11y) => <Switch id={a11y.id} checked={field.value} onCheckedChange={field.onChange} />}
</FormField>

// Radio group
<FormField control={form.control} name="plan" label="Billing">
  {(field) => (
    <RadioGroup value={field.value} onValueChange={field.onChange} className="flex gap-5">
      <label className="flex items-center gap-2"><RadioGroupItem value="monthly" />Monthly</label>
      <label className="flex items-center gap-2"><RadioGroupItem value="yearly" />Yearly</label>
    </RadioGroup>
  )}
</FormField>

// Text area with a live counter
<FormField control={form.control} name="bio" label="Bio" hint={`${form.watch("bio").length} / 280`}>
  {(field, a11y) => <Textarea {...field} {...a11y} rows={3} />}
</FormField>

4. Field without react-hook-form

<Field label="Workspace URL" hint="Letters, numbers and dashes." error={error}>
  {(a11y) => <Input {...a11y} value={slug} onChange={(e) => setSlug(e.target.value)} />}
</Field>

labelAction puts something on the label's right, e.g. a "Forgot password?" link.

5. PasswordInput

<PasswordInput value={pw} onChange={setPw} aria-label="Password" />                 // sign-in
<PasswordInput value={pw} onChange={setPw} showStrength aria-label="New password" /> // sign-up, reset

The strength meter scores the rules in DEFAULT_PASSWORD_RULES (12+ characters, a number, a symbol, mixed case). Pass rules to use your own:

rules={[{ label: "16+ characters", test: (v) => v.length >= 16 }]}

6. OtpInput

const [code, setCode] = useState("")
const [attempts, setAttempts] = useState(0)

<Shake trigger={attempts}>
  <OtpInput value={code} onChange={setCode} error={wrong}
    onComplete={async (c) => { if (!(await verify(c))) setAttempts((n) => n + 1) }} />
</Shake>
  • Typing moves to the next box.
  • Backspace clears the box and moves back.
  • The arrow keys move between boxes.
  • Pasting fills every box.
  • Phones offer the code from SMS (autocomplete="one-time-code").

Options: length (default 6), groupAfter (dash position, default 3), size, autoFocus, label.

7. Segmented

<Segmented
  label="Range"
  value={range}
  onChange={setRange}
  options={[
    { value: 7, label: "7D" },
    { value: 30, label: "30D" },
  ]}
  size="sm"
/>

It works with string, number or boolean values. Use it for two to five options that change what's on screen right away. Use a Select for longer lists.

8. Settings layout

FormSection gives the two-column settings look (stacked on phones):

<form className="rounded-xl border bg-card">
  <FormSection title="Photo" description="Shown on your profile.">…</FormSection>
  <FormSection title="Delete account" description="This can't be undone." danger>…</FormSection>
  <SaveBar … />
</form>