# Invalid / required

> A required switch in a form that shows an inline error message when submitted while off.

A shadcn/ui block from the [@flx](https://ui.flexnative.com) registry, listed on [shadcn.exchange](https://shadcn.exchange/r/flx/switch-11).

- Page, with a live preview: https://shadcn.exchange/r/flx/switch-11
- Screenshot: https://abzjhwgwpdpz7ua5.public.blob.vercel-storage.com/shots/flx/switch-11-light-ce5b82a0d4c55539.png
- Registry item: https://ui.flexnative.com/r/switch-11.json
- Listed: 2026-10-13, source last changed 2026-10-13

## Install

```bash
npx shadcn@latest add https://ui.flexnative.com/r/switch-11.json
```

Run it in a project that has shadcn/ui set up. It adds the files below and installs what they depend on.

## Dependencies

- npm packages: `sonner`
- Registry items: `switch`, `field`, `button`

## Files

### `registry/patterns/switch/switch-11.tsx`

```tsx
'use client'

import { useState } from 'react'
import { toast } from 'sonner'

import { Button } from '@/components/ui/button'
import {
  Field,
  FieldContent,
  FieldError,
  FieldLabel,
} from '@/components/ui/field'
import { Switch } from '@/components/ui/switch'

export function Switch11() {
  const [enabled, setEnabled] = useState(false)
  const [invalid, setInvalid] = useState(false)

  function onSubmit(event: React.FormEvent) {
    event.preventDefault()
    if (!enabled) {
      setInvalid(true)
      return
    }
    setInvalid(false)
    toast.success('Two-factor authentication enabled')
  }

  return (
    <form onSubmit={onSubmit} className="flex w-full max-w-sm flex-col gap-4">
      <Field orientation="horizontal" data-invalid={invalid}>
        <FieldContent>
          <FieldLabel htmlFor="switch-11">
            Enable two-factor authentication
          </FieldLabel>
          {invalid && (
            <FieldError>You must enable 2FA before continuing.</FieldError>
          )}
        </FieldContent>
        <Switch
          id="switch-11"
          aria-invalid={invalid}
          checked={enabled}
          onCheckedChange={(value) => {
            setEnabled(value)
            if (value) setInvalid(false)
          }}
        />
      </Field>
      <Button type="submit" size="sm" className="self-start">
        Continue
      </Button>
    </form>
  )
}
```
