@felte/validator-zod
v1.0.18
Published
A package to use Zod validation with Felte
Downloads
32,144
Maintainers
Readme
@felte/validator-zod
A package to help you handle validation with Zod in Felte.
Installation
npm install --save @felte/validator-zod zod
# Or, if you use yarn
yarn add @felte/validator-zod zod
Usage
Call validator
with an object containing your Zod schema in the schema
property. The result of the call can be passed as an extender to Felte:
import { validator } from '@felte/validator-zod';
import { z } from 'zod';
const schema = z.object({
email: z.string().email().nonempty(),
password: z.string().nonempty(),
});
const { form } = createForm({
// ...
extend: validator({ schema }), // or `extend: [validator({ schema })],`
// ...
});
OR use the validateSchema
function directly in the validate
option of createForm
. (No need to extend Felte).
import { validateSchema } from '@felte/validator-zod';
import { z } from 'zod';
const schema = z.object({
email: z.string().email().nonempty(),
password: z.string().nonempty(),
});
const { form } = createForm({
// ...
validate: validateSchema(schema),
// ...
});
Warnings
Optionally, you can tell this package to assign the results of your validations to your warnings
store by setting the level
property of the validator function to warning
. It's error
by default:
import { validator } from '@felte/validator-zod';
import { z } from 'zod';
const schema = z.object({
email: z.string().email().nonempty(),
password: z.string().nonempty(),
});
// We only warn if the user has started typing a value
const warnSchema = zod.object({
password: zod
.string()
.refine((value) => (value ? value.length > 8 : true), {
message: 'Password is not secure',
}),
});
const { form } = createForm({
// ...
extend: [
validator({ schema }),
validator({ schema: warnSchema, level: 'warning' }),
],
// ...
});
Typescript
Zod allows you to infer the type of your schema using z.infer
. This can be used so you don't need to create a type for your form's data:
import { z } from 'zod';
const schema = z.object({
email: z.string().email().nonempty(),
password: z.string().nonempty(),
});
const { form } = createForm<z.infer<typeof schema>>(/* ... */);