@felte/validator-zod
TypeScript icon, indicating that this package has built-in type declarations

1.0.17 • Public • Published

@felte/validator-zod

Tests Bundle size NPM Version codecov

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>>(/* ... */);

Package Sidebar

Install

npm i @felte/validator-zod

Weekly Downloads

13,946

Version

1.0.17

License

MIT

Unpacked Size

14.4 kB

Total Files

9

Last publish

Collaborators

  • pberganza