|
| 1 | +# Stimulus Zod Form |
| 2 | + |
| 3 | +### Stimulus Zod Validated Form |
| 4 | + |
| 5 | +For the ten people on earth who want to use [Zod](https://zod.dev/) with [Stimulus](https://stimulus.hotwired.dev/) for client side validation. |
| 6 | + |
| 7 | +This package was inspired by [Remix Validated Form](https://www.remix-validated-form.io/) but a whole lot simpler thanks to Stimulus! |
| 8 | + |
| 9 | +### Usage |
| 10 | + |
| 11 | +Define your schema and register the controllers |
| 12 | + |
| 13 | +```ts |
| 14 | +import { Application } from "@hotwired/stimulus" |
| 15 | +import { FormController, FieldController } from "stimulus-zod-form"; |
| 16 | +import { z } from "zod"; |
| 17 | + |
| 18 | +const PersonSchema = z.object({ |
| 19 | + name: z.string().min(3), |
| 20 | + email: z.string().email("invalid_email"), |
| 21 | + addresses: z.array(z.object({ city: z.string() })) |
| 22 | +}) |
| 23 | + |
| 24 | +const PersonFormController = FormController(PersonSchema); |
| 25 | + |
| 26 | +window.Stimulus = Application.start(); |
| 27 | +Stimulus.register("form", PersonFormController); |
| 28 | +Stimulus.register("field", FieldController); |
| 29 | +``` |
| 30 | + |
| 31 | +Let the controllers spring to life! |
| 32 | + |
| 33 | +```html |
| 34 | +<form data-controller="form" |
| 35 | + data-form-field-outlet=".form-field" |
| 36 | + data-action="form#submit" |
| 37 | + data-form-error-map-value='{ "invalid_email": "correo inválido", ... }'> |
| 38 | + |
| 39 | + <div data-form-target="error"></div> |
| 40 | + |
| 41 | + <div data-controller="field" class="form-field"> |
| 42 | + <input name="addresses[0].city" |
| 43 | + data-field-target="input" |
| 44 | + data-action="blur->field#setTouched blur->form#validate" /> |
| 45 | + <div data-field-target="error"></div> |
| 46 | + </div> |
| 47 | +</form> |
| 48 | +``` |
| 49 | + |
| 50 | +### Summary |
| 51 | + |
| 52 | +In the sample code above note the following |
| 53 | + |
| 54 | +* Form field outlets `data-form-field-outlet` |
| 55 | +* Form validate on submit `data-action="form#submit"` |
| 56 | +* Field validate on blur `data-action="blur->field#setTouched blur->form#validate"` |
| 57 | +* Field input target `data-field-target="input"` |
| 58 | +* Field error target `data-field-target="error"` |
| 59 | +* Form error target ` data-form-target="error"` |
| 60 | +* Error localization `data-form-error-map-value` |
0 commit comments