Skip to content

secondsky/claude-skills / plugins/react-hook-form-zod/skills/react-hook-form-zod

react-hook-form-zod

Verified

Type-safe React forms with React Hook Form and Zod validation. Use for form schemas, field arrays, multi-step forms, or encountering validation errors, resolver issues, nested field problems.

references/error-handling.md

View on GitHub
# Error Handling Guide

Complete guide for handling and displaying form errors.

---

## Error Display Patterns

### 1. Inline Errors (Recommended)

```typescript
<input {...register('email')} />
{errors.email && (
  <span role="alert" className="text-red-600">
    {errors.email.message}
  </span>
)}
```

### 2. Error Summary (Accessibility Best Practice)

```typescript
{Object.keys(errors).length > 0 && (
  <div role="alert" aria-live="assertive" className="error-summary">
    <h3>Please fix the following errors:</h3>
    <ul>
      {Object.entries(errors).map(([field, error]) => (
        <li key={field}>
          <strong>{field}:</strong> {error.message}
        </li>
      ))}
    </ul>
  </div>
)}
```

### 3. Toast Notifications

```typescript
const onError = (errors) => {
  toast.error(`Please fix ${Object.keys(errors).length} errors`)
}

<form onSubmit={handleSubmit(onSubmit, onError)}>
```

---

## ARIA Attributes

### Required Attributes

```typescript
<input
  {...register('email')}
  aria-invalid={errors.email ? 'true' : 'false'}
  aria-describedby={errors.email ? 'email-error' : undefined}
  aria-required="true"
/>
{errors.email && (
  <span id="email-error" role="alert">
    {errors.email.message}
  </span>
)}
```

---

## Custom Error Messages

### Method 1: In Zod Schema

```typescript
const schema = z.object({
  email: z.string()
    .min(1, 'Email is required')
    .email('Please enter a valid email address'),
  password: z.string()
    .min(8, { message: 'Password must be at least 8 characters long' }),
})
```

### Method 2: Global Error Callback (z.config)

In Zod 4, `z.setErrorMap` / `ZodErrorMap` are removed. Use `z.config()` for
global defaults, and callbacks return a bare `string` (or `undefined` to defer).

```typescript
z.config({
  customError: (issue) => {
    switch (issue.code) {
      case 'too_small':
        return `Must be at least ${issue.minimum} characters`
      case 'invalid_string':
        if (issue.validation === 'email') {
          return 'Please enter a valid email address'
        }
        return undefined
      default:
        return undefined // defer to default
    }
  },
})
```

---

## Error Formatting

### Flatten Errors for Forms

```typescript
try {
  schema.parse(data)
} catch (error) {
  if (error instanceof z.ZodError) {
    const formattedErrors = z.flattenError(error).fieldErrors
    // Result: { email: ['Invalid email'], password: ['Too short'] }
  }
}
```

### Format Errors for Display

```typescript
const formatError = (error: FieldError): string => {
  switch (error.type) {
    case 'required':
      return 'This field is required'
    case 'min':
      return `Minimum length is ${error.message}`
    case 'pattern':
      return 'Invalid format'
    default:
      return error.message || 'Invalid value'
  }
}
```

---

## Server Error Integration

```typescript
const onSubmit = async (data) => {
  try {
    const response = await fetch('/api/submit', {
      method: 'POST',
      body: JSON.stringify(data),
    })

    const result = await response.json()

    if (!result.success && result.errors) {
      // Map server errors to form fields
      Object.entries(result.errors).forEach(([field, message]) => {
        setError(field, {
          type: 'server',
          message: Array.isArray(message) ? message[0] : message,
        })
      })
    }
  } catch (error) {
    // Network error
    setError('root', {
      type: 'server',
      message: 'Unable to connect. Please try again.',
    })
  }
}
```

---

## Error Persistence

### Clear Errors on Input Change

```typescript
<input
  {...register('email')}
  onChange={(e) => {
    register('email').onChange(e)
    clearErrors('email') // Clear error when user starts typing
  }}
/>
```

### Clear All Errors on Submit Success

```typescript
const onSubmit = async (data) => {
  const success = await submitData(data)
  if (success) {
    reset() // Clears form and errors
  }
}
```

---

## Internationalization (i18n)

```typescript
import { useTranslation } from 'react-i18next'

const { t } = useTranslation()

const schema = z.object({
  email: z.email({ error: t('errors.invalidEmail') }),
  password: z.string().min(8, t('errors.passwordTooShort')),
})
```

---

## Error Components

### Reusable Error Display

```typescript
function FormError({ error }: { error?: FieldError }) {
  if (!error) return null

  return (
    <div role="alert" className="error">
      <svg className="icon">...</svg>
      <span>{error.message}</span>
    </div>
  )
}

// Usage
<FormError error={errors.email} />
```

### Field Group with Error

```typescript
function FieldGroup({ name, label, type = 'text', register, errors }) {
  return (
    <div className="field-group">
      <label htmlFor={name}>{label}</label>
      <input
        id={name}
        type={type}
        {...register(name)}
        aria-invalid={errors[name] ? 'true' : 'false'}
      />
      {errors[name] && <FormError error={errors[name]} />}
    </div>
  )
}
```

---

**Official Docs**: https://react-hook-form.com/
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall