Form

Schema-validated forms: typed field names, wired labels and errors, server errors on the right field, submit progress.

Status: stable. Category: Patterns.

import { Form, FormField, FormSubmit, FormError } from '@glyphui/ui/form'

Exports: Form, FormField, FormSubmit, FormError, useForm, formErrorStyles.

Notes

  • Works with any Standard Schema validator: zod, valibot, arktype.
  • Return { errors } from onSubmit for field errors; throw to show a form-level error in FormError.
  • FormSubmit outside <Form>, such as in a Modal footer, needs the form: <FormSubmit form={form}>.
  • Requires react-hook-form and @hookform/resolvers as peer dependencies.

FormField props

PropTypeDefaultDescription
children (required)(field: ControllerRenderProps<TInput, TName>) => ReactNodeRender the control and spread field onto it: {(field) => <Input {...field} />}.
control (required)Control<TInput, unknown, any>
name (required)stringTyped from the schema: a misspelled name is a compile error.
controlIdstringId for the control. Generated when omitted.
descriptionReactNode
disabledboolean
labelReactNode
labelActionReactNodeShown at the end of the label row, outside the label, so it is not part of the control's accessible name. For example a "Forgot password?" link.
orientation"horizontal" | "vertical"
requiredboolean

Example: Validation and server errors

Try an invalid email, or "[email protected]" for a server error.

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 page: https://glyphui.xyz/components/form