Skip to content

Commit

Permalink
feat(validator-zod): support parse params
Browse files Browse the repository at this point in the history
  • Loading branch information
nilscox committed Nov 5, 2024
1 parent ab1ae40 commit 2520c2d
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 4 deletions.
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
19 changes: 19 additions & 0 deletions packages/validator-zod/tests/validator.spec.ts
Original file line number Diff line number Diff line change
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'],
});
});
});

0 comments on commit 2520c2d

Please sign in to comment.