Install the plugin from npm:
npm install @goldencomm/alpine-plugin-zodbash
npm install @goldencomm/alpine-plugin-zod
`
Import it into your bundle alongside Alpine, and register it with Alpine.plugin():
`js
import Alpine from "alpinejs";
import zod from "@goldencomm/alpine-plugin-zod";
Alpine.plugin(zod);
Alpine.start();
`
Usage
The plugin adds $zod "magic", which gives you access to all of the methods and properties on the Zod object.
Basic usage:
`html
x-data="{
schema: $zod.object({
name: $zod.string().min(1),
}),
errors: {},
handleSubmit(e) {
const data = Object.fromEntries(new FormData(e.target));
const validation = this.schema.safeParse(data);
if (!validation.success) {
this.errors = validation.error.format();
return;
}
// ...do something
}
}"
x-on:submit.prevent="handleSubmit"
>
id="name"
type="text"
name="name"
aria-errormessage="error-name"
x-bind:aria-invalid="'name' in errors"
/>
``