@felte/验证器-zod
在 Felte 中帮助您处理 Zod 验证的软件包 .
安装
npm install --save @felte/validator-zod zod
# Or, if you use yarn
yarn add @felte/validator-zod zod
使用量
打电话 validator 含有您 Zod 策略的天体在 schema 属性。 调用的结果可以作为延伸器传递给费尔特:
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 })],`
// ...
});
使用 validateSchema 函数直接在 validate 选项 createForm. (不需要延长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 通过设置存储 level 校验函数的属性 warning这是 error 默认:
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' }),
],
// ...
});
字体
Zod允许您用 z.infer。这个可以使用,因此不需要为表单数据创建类型:
import { z } from 'zod';
const schema = z.object({
email: z.string().email().nonempty(),
password: z.string().nonempty(),
});
const { form } = createForm<z.infer<typeof schema>>(/* ... */);