added apps
This commit is contained in:
17
node_modules/@hookform/resolvers/zod/package.json
generated
vendored
Normal file
17
node_modules/@hookform/resolvers/zod/package.json
generated
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "@hookform/resolvers/zod",
|
||||
"amdName": "hookformResolversZod",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"description": "React Hook Form validation resolver: zod",
|
||||
"main": "dist/zod.js",
|
||||
"module": "dist/zod.module.js",
|
||||
"umd:main": "dist/zod.umd.js",
|
||||
"source": "src/index.ts",
|
||||
"types": "dist/index.d.ts",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"react-hook-form": "^7.55.0",
|
||||
"@hookform/resolvers": "^2.0.0"
|
||||
}
|
||||
}
|
||||
81
node_modules/@hookform/resolvers/zod/src/__tests__/Form-native-validation.tsx
generated
vendored
Normal file
81
node_modules/@hookform/resolvers/zod/src/__tests__/Form-native-validation.tsx
generated
vendored
Normal file
@@ -0,0 +1,81 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import user from '@testing-library/user-event';
|
||||
import React from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
import { zodResolver } from '..';
|
||||
|
||||
const USERNAME_REQUIRED_MESSAGE = 'username field is required';
|
||||
const PASSWORD_REQUIRED_MESSAGE = 'password field is required';
|
||||
|
||||
const schema = z.object({
|
||||
username: z.string().nonempty({ message: USERNAME_REQUIRED_MESSAGE }),
|
||||
password: z.string().nonempty({ message: PASSWORD_REQUIRED_MESSAGE }),
|
||||
});
|
||||
|
||||
type FormData = z.infer<typeof schema>;
|
||||
|
||||
interface Props {
|
||||
onSubmit: (data: FormData) => void;
|
||||
}
|
||||
|
||||
function TestComponent({ onSubmit }: Props) {
|
||||
const { register, handleSubmit } = useForm<FormData>({
|
||||
resolver: zodResolver(schema),
|
||||
shouldUseNativeValidation: true,
|
||||
});
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
<input {...register('username')} placeholder="username" />
|
||||
|
||||
<input {...register('password')} placeholder="password" />
|
||||
|
||||
<button type="submit">submit</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
test("form's native validation with Zod", async () => {
|
||||
const handleSubmit = vi.fn();
|
||||
render(<TestComponent onSubmit={handleSubmit} />);
|
||||
|
||||
// username
|
||||
let usernameField = screen.getByPlaceholderText(
|
||||
/username/i,
|
||||
) as HTMLInputElement;
|
||||
expect(usernameField.validity.valid).toBe(true);
|
||||
expect(usernameField.validationMessage).toBe('');
|
||||
|
||||
// password
|
||||
let passwordField = screen.getByPlaceholderText(
|
||||
/password/i,
|
||||
) as HTMLInputElement;
|
||||
expect(passwordField.validity.valid).toBe(true);
|
||||
expect(passwordField.validationMessage).toBe('');
|
||||
|
||||
await user.click(screen.getByText(/submit/i));
|
||||
|
||||
// username
|
||||
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
|
||||
expect(usernameField.validity.valid).toBe(false);
|
||||
expect(usernameField.validationMessage).toBe(USERNAME_REQUIRED_MESSAGE);
|
||||
|
||||
// password
|
||||
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
|
||||
expect(passwordField.validity.valid).toBe(false);
|
||||
expect(passwordField.validationMessage).toBe(PASSWORD_REQUIRED_MESSAGE);
|
||||
|
||||
await user.type(screen.getByPlaceholderText(/username/i), 'joe');
|
||||
await user.type(screen.getByPlaceholderText(/password/i), 'password');
|
||||
|
||||
// username
|
||||
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
|
||||
expect(usernameField.validity.valid).toBe(true);
|
||||
expect(usernameField.validationMessage).toBe('');
|
||||
|
||||
// password
|
||||
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
|
||||
expect(passwordField.validity.valid).toBe(true);
|
||||
expect(passwordField.validationMessage).toBe('');
|
||||
});
|
||||
48
node_modules/@hookform/resolvers/zod/src/__tests__/Form.tsx
generated
vendored
Normal file
48
node_modules/@hookform/resolvers/zod/src/__tests__/Form.tsx
generated
vendored
Normal file
@@ -0,0 +1,48 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import user from '@testing-library/user-event';
|
||||
import React from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
import { zodResolver } from '..';
|
||||
|
||||
const schema = z.object({
|
||||
username: z.string().nonempty({ message: 'username field is required' }),
|
||||
password: z.string().nonempty({ message: 'password field is required' }),
|
||||
});
|
||||
|
||||
function TestComponent({
|
||||
onSubmit,
|
||||
}: { onSubmit: (data: z.infer<typeof schema>) => void }) {
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm({
|
||||
resolver: zodResolver(schema), // Useful to check TypeScript regressions
|
||||
});
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
<input {...register('username')} />
|
||||
{errors.username && <span role="alert">{errors.username.message}</span>}
|
||||
|
||||
<input {...register('password')} />
|
||||
{errors.password && <span role="alert">{errors.password.message}</span>}
|
||||
|
||||
<button type="submit">submit</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
test("form's validation with Zod and TypeScript's integration", async () => {
|
||||
const handleSubmit = vi.fn();
|
||||
render(<TestComponent onSubmit={handleSubmit} />);
|
||||
|
||||
expect(screen.queryAllByRole('alert')).toHaveLength(0);
|
||||
|
||||
await user.click(screen.getByText(/submit/i));
|
||||
|
||||
expect(screen.getByText(/username field is required/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/password field is required/i)).toBeInTheDocument();
|
||||
expect(handleSubmit).not.toHaveBeenCalled();
|
||||
});
|
||||
88
node_modules/@hookform/resolvers/zod/src/__tests__/__fixtures__/data.ts
generated
vendored
Normal file
88
node_modules/@hookform/resolvers/zod/src/__tests__/__fixtures__/data.ts
generated
vendored
Normal file
@@ -0,0 +1,88 @@
|
||||
import { Field, InternalFieldName } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
|
||||
export const schema = z
|
||||
.object({
|
||||
username: z.string().regex(/^\w+$/).min(3).max(30),
|
||||
password: z
|
||||
.string()
|
||||
.regex(new RegExp('.*[A-Z].*'), 'One uppercase character')
|
||||
.regex(new RegExp('.*[a-z].*'), 'One lowercase character')
|
||||
.regex(new RegExp('.*\\d.*'), 'One number')
|
||||
.regex(
|
||||
new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'),
|
||||
'One special character',
|
||||
)
|
||||
.min(8, 'Must be at least 8 characters in length'),
|
||||
repeatPassword: z.string(),
|
||||
accessToken: z.union([z.string(), z.number()]),
|
||||
birthYear: z.number().min(1900).max(2013).optional(),
|
||||
email: z.string().email().optional(),
|
||||
tags: z.array(z.string()),
|
||||
enabled: z.boolean(),
|
||||
url: z.string().url('Custom error url').or(z.literal('')),
|
||||
like: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.number(),
|
||||
name: z.string().length(4),
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
dateStr: z
|
||||
.string()
|
||||
.transform((value) => new Date(value))
|
||||
.refine((value) => !isNaN(value.getTime()), {
|
||||
message: 'Invalid date',
|
||||
}),
|
||||
})
|
||||
.refine((obj) => obj.password === obj.repeatPassword, {
|
||||
message: 'Passwords do not match',
|
||||
path: ['confirm'],
|
||||
});
|
||||
|
||||
export const validData = {
|
||||
username: 'Doe',
|
||||
password: 'Password123_',
|
||||
repeatPassword: 'Password123_',
|
||||
birthYear: 2000,
|
||||
email: 'john@doe.com',
|
||||
tags: ['tag1', 'tag2'],
|
||||
enabled: true,
|
||||
accessToken: 'accessToken',
|
||||
url: 'https://react-hook-form.com/',
|
||||
like: [
|
||||
{
|
||||
id: 1,
|
||||
name: 'name',
|
||||
},
|
||||
],
|
||||
dateStr: '2020-01-01',
|
||||
} satisfies z.input<typeof schema>;
|
||||
|
||||
export const invalidData = {
|
||||
password: '___',
|
||||
email: '',
|
||||
birthYear: 'birthYear',
|
||||
like: [{ id: 'z' }],
|
||||
url: 'abc',
|
||||
} as unknown as z.input<typeof schema>;
|
||||
|
||||
export const fields: Record<InternalFieldName, Field['_f']> = {
|
||||
username: {
|
||||
ref: { name: 'username' },
|
||||
name: 'username',
|
||||
},
|
||||
password: {
|
||||
ref: { name: 'password' },
|
||||
name: 'password',
|
||||
},
|
||||
email: {
|
||||
ref: { name: 'email' },
|
||||
name: 'email',
|
||||
},
|
||||
birthday: {
|
||||
ref: { name: 'birthday' },
|
||||
name: 'birthday',
|
||||
},
|
||||
};
|
||||
430
node_modules/@hookform/resolvers/zod/src/__tests__/__snapshots__/zod.ts.snap
generated
vendored
Normal file
430
node_modules/@hookform/resolvers/zod/src/__tests__/__snapshots__/zod.ts.snap
generated
vendored
Normal file
@@ -0,0 +1,430 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`zodResolver > should return a single error from zodResolver when validation fails 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"accessToken": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
},
|
||||
"birthYear": {
|
||||
"message": "Expected number, received string",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
},
|
||||
"dateStr": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
},
|
||||
"email": {
|
||||
"message": "Invalid email",
|
||||
"ref": {
|
||||
"name": "email",
|
||||
},
|
||||
"type": "invalid_string",
|
||||
},
|
||||
"enabled": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
},
|
||||
"like": [
|
||||
{
|
||||
"id": {
|
||||
"message": "Expected number, received string",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
},
|
||||
"name": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
},
|
||||
},
|
||||
],
|
||||
"password": {
|
||||
"message": "One uppercase character",
|
||||
"ref": {
|
||||
"name": "password",
|
||||
},
|
||||
"type": "invalid_string",
|
||||
},
|
||||
"repeatPassword": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
},
|
||||
"tags": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
},
|
||||
"url": {
|
||||
"message": "Custom error url",
|
||||
"ref": undefined,
|
||||
"type": "invalid_string",
|
||||
},
|
||||
"username": {
|
||||
"message": "Required",
|
||||
"ref": {
|
||||
"name": "username",
|
||||
},
|
||||
"type": "invalid_type",
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`zodResolver > should return a single error from zodResolver with \`mode: sync\` when validation fails 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"accessToken": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
},
|
||||
"birthYear": {
|
||||
"message": "Expected number, received string",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
},
|
||||
"dateStr": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
},
|
||||
"email": {
|
||||
"message": "Invalid email",
|
||||
"ref": {
|
||||
"name": "email",
|
||||
},
|
||||
"type": "invalid_string",
|
||||
},
|
||||
"enabled": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
},
|
||||
"like": [
|
||||
{
|
||||
"id": {
|
||||
"message": "Expected number, received string",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
},
|
||||
"name": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
},
|
||||
},
|
||||
],
|
||||
"password": {
|
||||
"message": "One uppercase character",
|
||||
"ref": {
|
||||
"name": "password",
|
||||
},
|
||||
"type": "invalid_string",
|
||||
},
|
||||
"repeatPassword": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
},
|
||||
"tags": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
},
|
||||
"url": {
|
||||
"message": "Custom error url",
|
||||
"ref": undefined,
|
||||
"type": "invalid_string",
|
||||
},
|
||||
"username": {
|
||||
"message": "Required",
|
||||
"ref": {
|
||||
"name": "username",
|
||||
},
|
||||
"type": "invalid_type",
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`zodResolver > should return all the errors from zodResolver when validation fails with \`validateAllFieldCriteria\` set to true 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"accessToken": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
"types": {
|
||||
"invalid_type": [
|
||||
"Required",
|
||||
"Required",
|
||||
],
|
||||
"invalid_union": "Invalid input",
|
||||
},
|
||||
},
|
||||
"birthYear": {
|
||||
"message": "Expected number, received string",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
"types": {
|
||||
"invalid_type": "Expected number, received string",
|
||||
},
|
||||
},
|
||||
"dateStr": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
"types": {
|
||||
"invalid_type": "Required",
|
||||
},
|
||||
},
|
||||
"email": {
|
||||
"message": "Invalid email",
|
||||
"ref": {
|
||||
"name": "email",
|
||||
},
|
||||
"type": "invalid_string",
|
||||
"types": {
|
||||
"invalid_string": "Invalid email",
|
||||
},
|
||||
},
|
||||
"enabled": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
"types": {
|
||||
"invalid_type": "Required",
|
||||
},
|
||||
},
|
||||
"like": [
|
||||
{
|
||||
"id": {
|
||||
"message": "Expected number, received string",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
"types": {
|
||||
"invalid_type": "Expected number, received string",
|
||||
},
|
||||
},
|
||||
"name": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
"types": {
|
||||
"invalid_type": "Required",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
"password": {
|
||||
"message": "One uppercase character",
|
||||
"ref": {
|
||||
"name": "password",
|
||||
},
|
||||
"type": "invalid_string",
|
||||
"types": {
|
||||
"invalid_string": [
|
||||
"One uppercase character",
|
||||
"One lowercase character",
|
||||
"One number",
|
||||
],
|
||||
"too_small": "Must be at least 8 characters in length",
|
||||
},
|
||||
},
|
||||
"repeatPassword": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
"types": {
|
||||
"invalid_type": "Required",
|
||||
},
|
||||
},
|
||||
"tags": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
"types": {
|
||||
"invalid_type": "Required",
|
||||
},
|
||||
},
|
||||
"url": {
|
||||
"message": "Custom error url",
|
||||
"ref": undefined,
|
||||
"type": "invalid_string",
|
||||
"types": {
|
||||
"invalid_string": "Custom error url",
|
||||
},
|
||||
},
|
||||
"username": {
|
||||
"message": "Required",
|
||||
"ref": {
|
||||
"name": "username",
|
||||
},
|
||||
"type": "invalid_type",
|
||||
"types": {
|
||||
"invalid_type": "Required",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`zodResolver > should return all the errors from zodResolver when validation fails with \`validateAllFieldCriteria\` set to true and \`mode: sync\` 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"accessToken": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
"types": {
|
||||
"invalid_type": [
|
||||
"Required",
|
||||
"Required",
|
||||
],
|
||||
"invalid_union": "Invalid input",
|
||||
},
|
||||
},
|
||||
"birthYear": {
|
||||
"message": "Expected number, received string",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
"types": {
|
||||
"invalid_type": "Expected number, received string",
|
||||
},
|
||||
},
|
||||
"dateStr": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
"types": {
|
||||
"invalid_type": "Required",
|
||||
},
|
||||
},
|
||||
"email": {
|
||||
"message": "Invalid email",
|
||||
"ref": {
|
||||
"name": "email",
|
||||
},
|
||||
"type": "invalid_string",
|
||||
"types": {
|
||||
"invalid_string": "Invalid email",
|
||||
},
|
||||
},
|
||||
"enabled": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
"types": {
|
||||
"invalid_type": "Required",
|
||||
},
|
||||
},
|
||||
"like": [
|
||||
{
|
||||
"id": {
|
||||
"message": "Expected number, received string",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
"types": {
|
||||
"invalid_type": "Expected number, received string",
|
||||
},
|
||||
},
|
||||
"name": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
"types": {
|
||||
"invalid_type": "Required",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
"password": {
|
||||
"message": "One uppercase character",
|
||||
"ref": {
|
||||
"name": "password",
|
||||
},
|
||||
"type": "invalid_string",
|
||||
"types": {
|
||||
"invalid_string": [
|
||||
"One uppercase character",
|
||||
"One lowercase character",
|
||||
"One number",
|
||||
],
|
||||
"too_small": "Must be at least 8 characters in length",
|
||||
},
|
||||
},
|
||||
"repeatPassword": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
"types": {
|
||||
"invalid_type": "Required",
|
||||
},
|
||||
},
|
||||
"tags": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "invalid_type",
|
||||
"types": {
|
||||
"invalid_type": "Required",
|
||||
},
|
||||
},
|
||||
"url": {
|
||||
"message": "Custom error url",
|
||||
"ref": undefined,
|
||||
"type": "invalid_string",
|
||||
"types": {
|
||||
"invalid_string": "Custom error url",
|
||||
},
|
||||
},
|
||||
"username": {
|
||||
"message": "Required",
|
||||
"ref": {
|
||||
"name": "username",
|
||||
},
|
||||
"type": "invalid_type",
|
||||
"types": {
|
||||
"invalid_type": "Required",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`zodResolver > should return parsed values from zodResolver with \`mode: sync\` when validation pass 1`] = `
|
||||
{
|
||||
"errors": {},
|
||||
"values": {
|
||||
"accessToken": "accessToken",
|
||||
"birthYear": 2000,
|
||||
"dateStr": 2020-01-01T00:00:00.000Z,
|
||||
"email": "john@doe.com",
|
||||
"enabled": true,
|
||||
"like": [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "name",
|
||||
},
|
||||
],
|
||||
"password": "Password123_",
|
||||
"repeatPassword": "Password123_",
|
||||
"tags": [
|
||||
"tag1",
|
||||
"tag2",
|
||||
],
|
||||
"url": "https://react-hook-form.com/",
|
||||
"username": "Doe",
|
||||
},
|
||||
}
|
||||
`;
|
||||
161
node_modules/@hookform/resolvers/zod/src/__tests__/zod.ts
generated
vendored
Normal file
161
node_modules/@hookform/resolvers/zod/src/__tests__/zod.ts
generated
vendored
Normal file
@@ -0,0 +1,161 @@
|
||||
import { Resolver, SubmitHandler, useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
import { zodResolver } from '..';
|
||||
import { fields, invalidData, schema, validData } from './__fixtures__/data';
|
||||
|
||||
const shouldUseNativeValidation = false;
|
||||
|
||||
describe('zodResolver', () => {
|
||||
it('should return values from zodResolver when validation pass & raw=true', async () => {
|
||||
const parseAsyncSpy = vi.spyOn(schema, 'parseAsync');
|
||||
|
||||
const result = await zodResolver(schema, undefined, {
|
||||
raw: true,
|
||||
})(validData, undefined, {
|
||||
fields,
|
||||
shouldUseNativeValidation,
|
||||
});
|
||||
|
||||
expect(parseAsyncSpy).toHaveBeenCalledTimes(1);
|
||||
expect(result).toEqual({ errors: {}, values: validData });
|
||||
});
|
||||
|
||||
it('should return parsed values from zodResolver with `mode: sync` when validation pass', async () => {
|
||||
const parseSpy = vi.spyOn(schema, 'parse');
|
||||
const parseAsyncSpy = vi.spyOn(schema, 'parseAsync');
|
||||
|
||||
const result = await zodResolver(schema, undefined, {
|
||||
mode: 'sync',
|
||||
})(validData, undefined, { fields, shouldUseNativeValidation });
|
||||
|
||||
expect(parseSpy).toHaveBeenCalledTimes(1);
|
||||
expect(parseAsyncSpy).not.toHaveBeenCalled();
|
||||
expect(result.errors).toEqual({});
|
||||
expect(result).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return a single error from zodResolver when validation fails', async () => {
|
||||
const result = await zodResolver(schema)(invalidData, undefined, {
|
||||
fields,
|
||||
shouldUseNativeValidation,
|
||||
});
|
||||
|
||||
expect(result).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return a single error from zodResolver with `mode: sync` when validation fails', async () => {
|
||||
const parseSpy = vi.spyOn(schema, 'parse');
|
||||
const parseAsyncSpy = vi.spyOn(schema, 'parseAsync');
|
||||
|
||||
const result = await zodResolver(schema, undefined, {
|
||||
mode: 'sync',
|
||||
})(invalidData, undefined, { fields, shouldUseNativeValidation });
|
||||
|
||||
expect(parseSpy).toHaveBeenCalledTimes(1);
|
||||
expect(parseAsyncSpy).not.toHaveBeenCalled();
|
||||
expect(result).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return all the errors from zodResolver when validation fails with `validateAllFieldCriteria` set to true', async () => {
|
||||
const result = await zodResolver(schema)(invalidData, undefined, {
|
||||
fields,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
});
|
||||
|
||||
expect(result).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return all the errors from zodResolver when validation fails with `validateAllFieldCriteria` set to true and `mode: sync`', async () => {
|
||||
const result = await zodResolver(schema, undefined, { mode: 'sync' })(
|
||||
invalidData,
|
||||
undefined,
|
||||
{
|
||||
fields,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should throw any error unrelated to Zod', async () => {
|
||||
const schemaWithCustomError = schema.refine(() => {
|
||||
throw Error('custom error');
|
||||
});
|
||||
const promise = zodResolver(schemaWithCustomError)(validData, undefined, {
|
||||
fields,
|
||||
shouldUseNativeValidation,
|
||||
});
|
||||
|
||||
await expect(promise).rejects.toThrow('custom error');
|
||||
});
|
||||
|
||||
/**
|
||||
* Type inference tests
|
||||
*/
|
||||
it('should correctly infer the output type from a zod schema', () => {
|
||||
const resolver = zodResolver(z.object({ id: z.number() }));
|
||||
|
||||
expectTypeOf(resolver).toEqualTypeOf<
|
||||
Resolver<{ id: number }, unknown, { id: number }>
|
||||
>();
|
||||
});
|
||||
|
||||
it('should correctly infer the output type from a zod schema using a transform', () => {
|
||||
const resolver = zodResolver(
|
||||
z.object({ id: z.number().transform((val) => String(val)) }),
|
||||
);
|
||||
|
||||
expectTypeOf(resolver).toEqualTypeOf<
|
||||
Resolver<{ id: number }, unknown, { id: string }>
|
||||
>();
|
||||
});
|
||||
|
||||
it('should correctly infer the output type from a zod schema when a different input type is specified', () => {
|
||||
const schema = z.object({ id: z.number() }).transform(({ id }) => {
|
||||
return { id: String(id) };
|
||||
});
|
||||
|
||||
const resolver = zodResolver<{ id: number }, any, z.output<typeof schema>>(
|
||||
schema,
|
||||
);
|
||||
|
||||
expectTypeOf(resolver).toEqualTypeOf<
|
||||
Resolver<{ id: number }, any, { id: string }>
|
||||
>();
|
||||
});
|
||||
|
||||
it('should correctly infer the output type from a Zod schema for the handleSubmit function in useForm', () => {
|
||||
const schema = z.object({ id: z.number() });
|
||||
|
||||
const form = useForm({
|
||||
resolver: zodResolver(schema),
|
||||
});
|
||||
|
||||
expectTypeOf(form.watch('id')).toEqualTypeOf<number>();
|
||||
|
||||
expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
|
||||
SubmitHandler<{
|
||||
id: number;
|
||||
}>
|
||||
>();
|
||||
});
|
||||
|
||||
it('should correctly infer the output type from a Zod schema with a transform for the handleSubmit function in useForm', () => {
|
||||
const schema = z.object({ id: z.number().transform((val) => String(val)) });
|
||||
|
||||
const form = useForm({
|
||||
resolver: zodResolver(schema),
|
||||
});
|
||||
|
||||
expectTypeOf(form.watch('id')).toEqualTypeOf<number>();
|
||||
|
||||
expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
|
||||
SubmitHandler<{
|
||||
id: string;
|
||||
}>
|
||||
>();
|
||||
});
|
||||
});
|
||||
1
node_modules/@hookform/resolvers/zod/src/index.ts
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/zod/src/index.ts
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export * from './zod';
|
||||
141
node_modules/@hookform/resolvers/zod/src/zod.ts
generated
vendored
Normal file
141
node_modules/@hookform/resolvers/zod/src/zod.ts
generated
vendored
Normal file
@@ -0,0 +1,141 @@
|
||||
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
|
||||
import {
|
||||
FieldError,
|
||||
FieldErrors,
|
||||
FieldValues,
|
||||
Resolver,
|
||||
ResolverError,
|
||||
ResolverSuccess,
|
||||
appendErrors,
|
||||
} from 'react-hook-form';
|
||||
import { ZodError, z } from 'zod';
|
||||
|
||||
const isZodError = (error: any): error is ZodError =>
|
||||
Array.isArray(error?.errors);
|
||||
|
||||
function parseErrorSchema(
|
||||
zodErrors: z.ZodIssue[],
|
||||
validateAllFieldCriteria: boolean,
|
||||
) {
|
||||
const errors: Record<string, FieldError> = {};
|
||||
for (; zodErrors.length; ) {
|
||||
const error = zodErrors[0];
|
||||
const { code, message, path } = error;
|
||||
const _path = path.join('.');
|
||||
|
||||
if (!errors[_path]) {
|
||||
if ('unionErrors' in error) {
|
||||
const unionError = error.unionErrors[0].errors[0];
|
||||
|
||||
errors[_path] = {
|
||||
message: unionError.message,
|
||||
type: unionError.code,
|
||||
};
|
||||
} else {
|
||||
errors[_path] = { message, type: code };
|
||||
}
|
||||
}
|
||||
|
||||
if ('unionErrors' in error) {
|
||||
error.unionErrors.forEach((unionError) =>
|
||||
unionError.errors.forEach((e) => zodErrors.push(e)),
|
||||
);
|
||||
}
|
||||
|
||||
if (validateAllFieldCriteria) {
|
||||
const types = errors[_path].types;
|
||||
const messages = types && types[error.code];
|
||||
|
||||
errors[_path] = appendErrors(
|
||||
_path,
|
||||
validateAllFieldCriteria,
|
||||
errors,
|
||||
code,
|
||||
messages
|
||||
? ([] as string[]).concat(messages as string[], error.message)
|
||||
: error.message,
|
||||
) as FieldError;
|
||||
}
|
||||
|
||||
zodErrors.shift();
|
||||
}
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
export function zodResolver<Input extends FieldValues, Context, Output>(
|
||||
schema: z.ZodSchema<Output, any, Input>,
|
||||
schemaOptions?: Partial<z.ParseParams>,
|
||||
resolverOptions?: {
|
||||
mode?: 'async' | 'sync';
|
||||
raw?: false;
|
||||
},
|
||||
): Resolver<Input, Context, Output>;
|
||||
|
||||
export function zodResolver<Input extends FieldValues, Context, Output>(
|
||||
schema: z.ZodSchema<Output, any, Input>,
|
||||
schemaOptions: Partial<z.ParseParams> | undefined,
|
||||
resolverOptions: {
|
||||
mode?: 'async' | 'sync';
|
||||
raw: true;
|
||||
},
|
||||
): Resolver<Input, Context, Input>;
|
||||
|
||||
/**
|
||||
* Creates a resolver function for react-hook-form that validates form data using a Zod schema
|
||||
* @param {z.ZodSchema<Input>} schema - The Zod schema used to validate the form data
|
||||
* @param {Partial<z.ParseParams>} [schemaOptions] - Optional configuration options for Zod parsing
|
||||
* @param {Object} [resolverOptions] - Optional resolver-specific configuration
|
||||
* @param {('async'|'sync')} [resolverOptions.mode='async'] - Validation mode. Use 'sync' for synchronous validation
|
||||
* @param {boolean} [resolverOptions.raw=false] - If true, returns the raw form values instead of the parsed data
|
||||
* @returns {Resolver<z.output<typeof schema>>} A resolver function compatible with react-hook-form
|
||||
* @throws {Error} Throws if validation fails with a non-Zod error
|
||||
* @example
|
||||
* const schema = z.object({
|
||||
* name: z.string().min(2),
|
||||
* age: z.number().min(18)
|
||||
* });
|
||||
*
|
||||
* useForm({
|
||||
* resolver: zodResolver(schema)
|
||||
* });
|
||||
*/
|
||||
export function zodResolver<Input extends FieldValues, Context, Output>(
|
||||
schema: z.ZodSchema<Output, any, Input>,
|
||||
schemaOptions?: Partial<z.ParseParams>,
|
||||
resolverOptions: {
|
||||
mode?: 'async' | 'sync';
|
||||
raw?: boolean;
|
||||
} = {},
|
||||
): Resolver<Input, Context, Output | Input> {
|
||||
return async (values: Input, _, options) => {
|
||||
try {
|
||||
const data = await schema[
|
||||
resolverOptions.mode === 'sync' ? 'parse' : 'parseAsync'
|
||||
](values, schemaOptions);
|
||||
|
||||
options.shouldUseNativeValidation && validateFieldsNatively({}, options);
|
||||
|
||||
return {
|
||||
errors: {} as FieldErrors,
|
||||
values: resolverOptions.raw ? Object.assign({}, values) : data,
|
||||
} satisfies ResolverSuccess<Output | Input>;
|
||||
} catch (error) {
|
||||
if (isZodError(error)) {
|
||||
return {
|
||||
values: {},
|
||||
errors: toNestErrors(
|
||||
parseErrorSchema(
|
||||
error.errors,
|
||||
!options.shouldUseNativeValidation &&
|
||||
options.criteriaMode === 'all',
|
||||
),
|
||||
options,
|
||||
),
|
||||
} satisfies ResolverError<Input>;
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user