@goldencomm/alpine-plugin-zod
v1.0.1
Published
Install the plugin from npm:
Downloads
3
Readme
@goldencomm/alpine-plugin-zod
Installation
Install the plugin from npm:
npm install @goldencomm/alpine-plugin-zod
Import it into your bundle alongside Alpine, and register it with Alpine.plugin()
:
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:
<form
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"
>
<div>
<label for="name">Name</label>
<input
id="name"
type="text"
name="name"
aria-errormessage="error-name"
x-bind:aria-invalid="'name' in errors"
/>
<div id="error-name" role="alert" aria-live="polite">
<template x-if="'name' in errors">
<template x-for="error in errors.name._errors">
<p x-text="error"></p>
</template>
</template>
</div>
</div>
<button>Submit</button>
</form>