Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support parse params in zod validator #302

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
feat(validator-zod): support parse params
  • Loading branch information
nilscox committed Nov 5, 2024
commit c058d37c312ca95c277bc9ae3f2b928ba7bdb595
25 changes: 25 additions & 0 deletions packages/validator-zod/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,28 @@ const schema = z.object({

const { form } = createForm<z.infer<typeof schema>>(/* ... */);
```

## Error messages

The `validator` function accepts a `params` option that will be forwarded to zod, including [a contextual errorMap](https://zod.dev/ERROR_HANDLING?id=contextual-error-map) used to customize error messages. This parameter can be passed as second argument to the `validateSchema` function.

```javascript
import { validator } from '@felte/validator-zod';
import { z } from 'zod';

const schema = z.object({
email: z.string().email().nonempty(),
password: z.string().nonempty(),
});

const errorMap: zod.ZodErrorMap = (error) => {
// Error messages logic
return { message: '' };
};

const { form } = createForm({
// ...
extend: validator({ schema }, { errorMap }), // or `validateSchema(schema, { errorMap })`
// ...
});
```
11 changes: 7 additions & 4 deletions packages/validator-zod/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,17 @@ import type {
Extender,
} from '@felte/common';
import { _update } from '@felte/common';
import type { ZodError, ZodSchema } from 'zod';
import type { ParseParams, ZodError, ZodSchema } from 'zod';

export type ValidatorConfig<Data extends Obj = Obj> = {
schema: ZodSchema<Data>;
level?: 'error' | 'warning';
params?: Partial<ParseParams>;
};

export function validateSchema<Data extends Obj>(
schema: ZodSchema
schema: ZodSchema,
params?: Partial<ParseParams>
): ValidationFunction<Data> {
function walk(
error: ZodError,
Expand Down Expand Up @@ -45,7 +47,7 @@ export function validateSchema<Data extends Obj>(
return async function validate(
values: Data
): Promise<AssignableErrors<Data> | undefined> {
const result = await schema.safeParseAsync(values);
const result = await schema.safeParseAsync(values, params);
if (!result.success) {
let err = {} as AssignableErrors<Data>;
err = walk(result.error, err);
Expand All @@ -57,12 +59,13 @@ export function validateSchema<Data extends Obj>(
export function validator<Data extends Obj = Obj>({
schema,
level = 'error',
params,
}: ValidatorConfig): Extender<Data> {
return function extender(
currentForm: CurrentForm<Data>
): ExtenderHandler<Data> {
if (currentForm.stage !== 'SETUP') return {};
const validateFn = validateSchema<Data>(schema);
const validateFn = validateSchema<Data>(schema, params);
currentForm.addValidator(validateFn, { level });
return {};
};
Expand Down
21 changes: 20 additions & 1 deletion packages/validator-zod/tests/validator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import '@testing-library/jest-dom/vitest';
import { expect, describe, test, vi } from 'vitest';
import { createForm } from './common';
import { validateSchema, validator } from '../src';
import { z, ZodSchema } from 'zod';
import { z, ZodErrorMap, ZodSchema } from 'zod';
import { get } from 'svelte/store';

type Data = {
Expand Down Expand Up @@ -363,4 +363,23 @@ describe('Validator zod', () => {

expect(errors).to.deep.equal({ type: ['Oops'] });
});

test('forwards parse parameters to zod', async () => {
const schema = z.object({ foo: z.literal('foo') });

const errorMap: ZodErrorMap = () => {
return { message: 'Oops' };
};

const { validate, errors } = createForm({
initialValues: { foo: 'bar' },
extend: validator({ schema, params: { errorMap } }),
});

await validate();

expect(get(errors)).to.deep.equal({
foo: ['Oops'],
});
});
});
Loading