Forms

Schema-validated forms with server errors, in pages and modals.

@glyphui/ui/form wraps react-hook-form with a schema and Glyph's fields. You describe the data once; field names, values and errors are typed from it, and labels, descriptions, error messages and aria-* attributes are wired for you.

npm install react-hook-form @hookform/resolvers zod

Any Standard Schema validator works: zod, valibot, arktype.

A form

import { Input } from '@glyphui/ui'
import { Form, FormError, FormField, FormSubmit, useForm } from '@glyphui/ui/form'
import { z } from 'zod'

const schema = z.object({
  name: z.string().trim().min(2, 'Use at least 2 characters'),
  email: z.email('Enter a valid email address'),
})

async function createAccount(values: z.infer<typeof schema>) {
  const res = await fetch('/api/accounts', { method: 'POST', body: JSON.stringify(values) })
  return res.status === 409 ? 'taken' : 'ok'
}

export function SignupForm() {
  const form = useForm({ schema, defaultValues: { name: '', email: '' } })
  return (
    <Form
      form={form}
      className="grid max-w-sm gap-4"
      onSubmit={async (values) => {
        if ((await createAccount(values)) === 'taken')
          return { errors: { email: 'That email is already registered.' } }
      }}
    >
      <FormError />
      <FormField control={form.control} name="name" label="Name" required>
        {(field) => <Input autoComplete="name" {...field} />}
      </FormField>
      <FormField control={form.control} name="email" label="Email" required>
        {(field) => <Input type="email" autoComplete="email" {...field} />}
      </FormField>
      <FormSubmit>Create account</FormSubmit>
    </Form>
  )
}
import { Input, Text } from '@glyphui/ui'
import { Form, FormError, FormField, FormSubmit, useForm } from '@glyphui/ui/form'
import { useState } from 'react'
import { z } from 'zod'

const schema = z.object({
  name: z.string().trim().min(2, 'Use at least 2 characters'),
  email: z.email('Enter a valid email address'),
})

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

export default function Example() {
  const [done, setDone] = useState<string | null>(null)
  const form = useForm({ schema, defaultValues: { name: '', email: '' } })

  if (done) return <Text>Welcome aboard, {done}.</Text>

  return (
    <Form
      form={form}
      className="grid max-w-sm gap-4"
      onSubmit={async (values) => {
        await wait(700)
        if (values.email === '[email protected]')
          return { errors: { email: 'That email is already registered.' } }
        setDone(values.name)
      }}
    >
      <FormError />
      <FormField control={form.control} name="name" label="Name" required>
        {(field) => <Input autoComplete="name" {...field} />}
      </FormField>
      <FormField control={form.control} name="email" label="Email" required>
        {(field) => <Input type="email" autoComplete="email" {...field} />}
      </FormField>
      <FormSubmit className="justify-self-start">Create account</FormSubmit>
    </Form>
  )
}

Live example: https://glyphui.xyz/components/form

  • name is checked against the schema: a typo is a compile error.
  • onSubmit only runs with valid values, already parsed by the schema.
  • FormSubmit shows a spinner and blocks double submits until onSubmit settles.

Server errors

What onSubmit returns or throws decides what the user sees:

From onSubmitShown
{ errors: { email: '…' } }Under the matching field
{ errors: { root: '…' } }In FormError, above the form
A thrown errorIts message in FormError
NothingNothing; reset or navigate as you like

A field's server error clears as soon as the user edits that field.

Other field types

FormField passes react-hook-form's field ({ value, onChange, onBlur, name, ref }) to its child. Glyph inputs inside a field pick up its label, description and error wiring on their own. Text inputs take the field with {...field}; controls with a value / onValueChange API map it explicitly:

import { DatePicker, NumberInput, Select, SelectItem } from '@glyphui/ui'
import { Form, FormField, useForm } from '@glyphui/ui/form'
import { z } from 'zod'

const schema = z.object({
  plan: z.enum(['starter', 'growth']),
  seats: z.number().int().min(1),
  startsOn: z.date('Choose a start date'),
})

export function PlanFields() {
  const form = useForm({ schema, defaultValues: { plan: 'starter', seats: 5 } })
  return (
    <Form form={form} onSubmit={() => {}} className="grid gap-4">
      <FormField control={form.control} name="plan" label="Plan">
        {(field) => (
          <Select value={field.value} onValueChange={field.onChange}>
            <SelectItem value="starter">Starter</SelectItem>
            <SelectItem value="growth">Growth</SelectItem>
          </Select>
        )}
      </FormField>
      <FormField control={form.control} name="seats" label="Seats">
        {(field) => (
          <NumberInput
            value={field.value ?? null}
            onValueChange={(v) => field.onChange(v ?? undefined)}
            min={1}
          />
        )}
      </FormField>
      <FormField control={form.control} name="startsOn" label="Starts on">
        {(field) => <DatePicker value={field.value} onValueChange={field.onChange} />}
      </FormField>
    </Form>
  )
}

NumberInput reports the value while you type, so a field error clears before you reach the submit button.

Forms in a Modal

A Modal's footer sits outside the form element, so give FormSubmit the form explicitly:

import {
  Button,
  DatePicker,
  Input,
  Modal,
  ModalClose,
  NumberInput,
  Select,
  SelectItem,
  toast,
} from '@glyphui/ui'
import { Form, FormError, FormField, FormSubmit, useForm } from '@glyphui/ui/form'
import { Plus } from 'lucide-react'
import { useState } from 'react'
import { z } from 'zod'

const customers = ['Northwind', 'Globex', 'Initech', 'Umbrella']

const schema = z.object({
  customer: z.string().min(1, 'Choose a customer'),
  amount: z.number('Enter an amount').positive('Must be more than zero'),
  due: z.date('Choose a due date'),
  memo: z.string().max(140, 'Keep it under 140 characters'),
})

const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' })

export default function Example() {
  const [open, setOpen] = useState(false)
  const form = useForm({
    schema,
    defaultValues: { customer: '', amount: undefined, due: undefined, memo: '' },
  })

  return (
    <Modal
      open={open}
      onOpenChange={(next) => {
        if (!next) form.reset()
        setOpen(next)
      }}
      title="New invoice"
      description="The customer gets an email with a payment link."
      trigger={<Button leftIcon={<Plus />}>New invoice</Button>}
      footer={
        <>
          <ModalClose asChild>
            <Button variant="outline">Cancel</Button>
          </ModalClose>
          {/* Outside <Form>, so it gets the form explicitly. */}
          <FormSubmit form={form}>Create invoice</FormSubmit>
        </>
      }
    >
      <Form
        form={form}
        className="grid gap-4"
        onSubmit={async (values) => {
          await new Promise((resolve) => setTimeout(resolve, 600))
          if (values.amount > 50_000) {
            return { errors: { amount: 'Invoices over $50,000 need approval.' } }
          }
          toast.success('Invoice created', {
            description: `${values.customer} · ${usd.format(values.amount)}`,
          })
          setOpen(false)
          form.reset()
        }}
      >
        <FormError />
        <FormField control={form.control} name="customer" label="Customer" required>
          {(field) => (
            <Select
              placeholder="Choose a customer"
              value={field.value}
              onValueChange={field.onChange}
            >
              {customers.map((name) => (
                <SelectItem key={name} value={name}>
                  {name}
                </SelectItem>
              ))}
            </Select>
          )}
        </FormField>
        <div className="grid gap-4 sm:grid-cols-2">
          <FormField control={form.control} name="amount" label="Amount" required>
            {(field) => (
              <NumberInput
                value={field.value ?? null}
                onValueChange={(value) => field.onChange(value ?? undefined)}
                min={0}
                locale="en-US"
                formatOptions={{ style: 'currency', currency: 'USD' }}
              />
            )}
          </FormField>
          <FormField control={form.control} name="due" label="Due date" required>
            {(field) => (
              <DatePicker value={field.value} onValueChange={field.onChange} minDate={new Date()} />
            )}
          </FormField>
        </div>
        <FormField
          control={form.control}
          name="memo"
          label="Memo"
          description="Shown on the invoice."
        >
          {(field) => <Input placeholder="October usage" {...field} />}
        </FormField>
      </Form>
    </Modal>
  )
}

Live example: https://glyphui.xyz/components/modal

For a plain form without the form pattern, pass onSubmit to Modal instead: its body and footer become one <form>, and a type="submit" button in the footer works.

Confirmations

For "are you sure?" questions, skip the form: useConfirm() opens a themed confirmation dialog and resolves to true or false.

import { Button, useConfirm } from '@glyphui/ui'

export function DeleteButton({ onDelete }: { onDelete: () => void }) {
  const confirm = useConfirm()
  return (
    <Button
      variant="danger"
      onClick={async () => {
        if (await confirm({ title: 'Delete project?', tone: 'danger' })) onDelete()
      }}
    >
      Delete
    </Button>
  )
}

Live page: https://glyphui.xyz/docs/forms