feat: ZodForm

This commit is contained in:
严浩
2024-11-20 16:24:48 +08:00
parent c9c4d523c1
commit 998cb5d4e3
7 changed files with 382 additions and 266 deletions

77
src/zod-form/index.vue Normal file
View File

@@ -0,0 +1,77 @@
<script setup lang="ts">
import { createZodPlugin } from '@formkit/zod'
import { z } from 'zod'
// https://github.com/aiji42/zod-i18n?tab=readme-ov-file#how-to-use
import i18next from "i18next";
import { zodI18nMap } from "zod-i18n-map";
// Import your language translation files
import translation from "zod-i18n-map/locales/zh-CN/zod.json";
// lng and resources key depend on your locale.
i18next.init({
lng: "es",
resources: {
es: { zod: translation },
},
});
z.setErrorMap(zodI18nMap);
const zodSchema = z.object({
personalInfo: z.object({
firstName: z.string().min(3).max(25),
lastName: z.string().min(3).max(25),
}),
email: z.string().email(),
arrayMin: z.string().array().min(2),
})
const [zodPlugin, submitHandler] = createZodPlugin(
zodSchema,
async (formData) => {
// fake submit handler, but this is where you
// do something with your valid data.
await new Promise((r) => setTimeout(r, 1000))
alert('Form was submitted!')
console.log(formData)
}
)
</script>
<template>
<div class="bg-white rounded-xl shadow-xl p-8 mx-auto my-16 max-w-[450px]">
<h1>Validation from Zod schema</h1>
<FormKit
type="form"
:plugins="[zodPlugin]"
@submit="submitHandler"
>
<FormKit
type="group"
name="personalInfo"
>
<FormKit
validation-visibility="live"
type="text"
name="firstName"
label="First Name"
/>
<FormKit
type="text"
name="lastName"
label="Last Name"
/>
</FormKit>
<FormKit
type="text"
name="email"
label="Your email"
/>
<FormKit
type="checkbox"
name="arrayMin"
label="Zod features"
:options="['Validation', 'Type-Safety', 'Reusability']"
/>
</FormKit>
</div>
</template>