---
globs: **/*form*.tsx,**/*Form*.tsx
---

# Forms and Validation

## Form Library Stack

- **Forms**: react-hook-form for form state management
- **Validation**: Zod schemas for type-safe validation
- **Resolvers**: @hookform/resolvers for integration

## Form Structure

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

// Define schema
const formSchema = z.object({
  name: z.string().min(1, 'Name is required'),
  email: z.string().email('Invalid email address'),
  message: z.string().min(10, 'Message must be at least 10 characters')
})

type FormData = z.infer<typeof formSchema>

export function ContactForm() {
  const form = useForm<FormData>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: '',
      email: '',
      message: ''
    }
  })

  const onSubmit = (data: FormData) => {
    // Handle form submission
  }

  return (
    <form onSubmit={form.handleSubmit(onSubmit)}>
      {/* Form fields with error handling */}
    </form>
  )
}
```

## Error Handling Rules

1. **Field-level errors**: Show validation errors under each field
2. **Generic submit error**: Display general submission errors
3. **Never swallow errors**: Always surface validation and submission errors
4. **Loading states**: Show loading indicators during submission

## Form Components

Use shadcn/ui form components from [src/components/ui/form.tsx](mdc:src/components/ui/form.tsx):

```typescript
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'

<FormField
  control={form.control}
  name="email"
  render={({ field }) => (
    <FormItem>
      <FormLabel>Email</FormLabel>
      <FormControl>
        <Input placeholder="your@email.com" {...field} />
      </FormControl>
      <FormMessage />
    </FormItem>
  )}
/>
```

## Validation Patterns

- Use Zod for all form validation
- Provide clear, user-friendly error messages
- Validate on both client and server side
- Handle async validation (e.g., email uniqueness)