added apps
This commit is contained in:
19
node_modules/@hookform/resolvers/standard-schema/package.json
generated
vendored
Normal file
19
node_modules/@hookform/resolvers/standard-schema/package.json
generated
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "@hookform/resolvers/standard-schema",
|
||||
"amdName": "hookformResolversStandardSchema",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"description": "React Hook Form validation resolver: standard-schema",
|
||||
"main": "dist/standard-schema.js",
|
||||
"module": "dist/standard-schema.module.js",
|
||||
"umd:main": "dist/standard-schema.umd.js",
|
||||
"source": "src/index.ts",
|
||||
"types": "dist/index.d.ts",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"react-hook-form": "^7.55.0",
|
||||
"@standard-schema/spec": "^1.0.0",
|
||||
"@standard-schema/utils": "^0.3.0",
|
||||
"@hookform/resolvers": "^2.0.0"
|
||||
}
|
||||
}
|
||||
82
node_modules/@hookform/resolvers/standard-schema/src/__tests__/Form-native-validation.tsx
generated
vendored
Normal file
82
node_modules/@hookform/resolvers/standard-schema/src/__tests__/Form-native-validation.tsx
generated
vendored
Normal file
@@ -0,0 +1,82 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import user from '@testing-library/user-event';
|
||||
import { type } from 'arktype';
|
||||
import React from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { standardSchemaResolver } from '..';
|
||||
|
||||
const schema = type({
|
||||
username: 'string>1',
|
||||
password: 'string>1',
|
||||
});
|
||||
|
||||
type FormData = typeof schema.infer;
|
||||
|
||||
interface Props {
|
||||
onSubmit: (data: FormData) => void;
|
||||
}
|
||||
|
||||
function TestComponent({ onSubmit }: Props) {
|
||||
const { register, handleSubmit } = useForm<FormData>({
|
||||
resolver: standardSchemaResolver(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 arkType", 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 must be at least length 2',
|
||||
);
|
||||
|
||||
// password
|
||||
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
|
||||
expect(passwordField.validity.valid).toBe(false);
|
||||
expect(passwordField.validationMessage).toBe(
|
||||
'password must be at least length 2',
|
||||
);
|
||||
|
||||
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('');
|
||||
});
|
||||
54
node_modules/@hookform/resolvers/standard-schema/src/__tests__/Form.tsx
generated
vendored
Normal file
54
node_modules/@hookform/resolvers/standard-schema/src/__tests__/Form.tsx
generated
vendored
Normal file
@@ -0,0 +1,54 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import user from '@testing-library/user-event';
|
||||
import { type } from 'arktype';
|
||||
import React from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { standardSchemaResolver } from '..';
|
||||
|
||||
const schema = type({
|
||||
username: 'string>1',
|
||||
password: 'string>1',
|
||||
});
|
||||
|
||||
function TestComponent({
|
||||
onSubmit,
|
||||
}: {
|
||||
onSubmit: (data: typeof schema.infer) => void;
|
||||
}) {
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm({
|
||||
resolver: standardSchemaResolver(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 arkType 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 must be at least length 2'),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText('password must be at least length 2'),
|
||||
).toBeInTheDocument();
|
||||
expect(handleSubmit).not.toHaveBeenCalled();
|
||||
});
|
||||
111
node_modules/@hookform/resolvers/standard-schema/src/__tests__/__fixtures__/data.ts
generated
vendored
Normal file
111
node_modules/@hookform/resolvers/standard-schema/src/__tests__/__fixtures__/data.ts
generated
vendored
Normal file
@@ -0,0 +1,111 @@
|
||||
import { StandardSchemaV1 } from '@standard-schema/spec';
|
||||
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-01T00:00:00.000Z',
|
||||
} 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',
|
||||
},
|
||||
};
|
||||
|
||||
export const customSchema: StandardSchemaV1<
|
||||
StandardSchemaV1.InferInput<typeof schema>,
|
||||
StandardSchemaV1.InferOutput<typeof schema>
|
||||
> = {
|
||||
'~standard': {
|
||||
version: 1,
|
||||
vendor: 'custom',
|
||||
validate: () => ({
|
||||
issues: [
|
||||
{
|
||||
path: [{ key: 'username' }],
|
||||
message: 'Custom error',
|
||||
},
|
||||
{
|
||||
path: [{ key: 'like' }, { key: 0 }, { key: 'id' }],
|
||||
message: 'Custom error',
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
};
|
||||
274
node_modules/@hookform/resolvers/standard-schema/src/__tests__/__snapshots__/standard-schema.ts.snap
generated
vendored
Normal file
274
node_modules/@hookform/resolvers/standard-schema/src/__tests__/__snapshots__/standard-schema.ts.snap
generated
vendored
Normal file
@@ -0,0 +1,274 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`standardSchemaResolver > should correctly handle path segments that are objects 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"like": [
|
||||
{
|
||||
"id": {
|
||||
"message": "Custom error",
|
||||
"ref": undefined,
|
||||
"type": "",
|
||||
},
|
||||
},
|
||||
],
|
||||
"username": {
|
||||
"message": "Custom error",
|
||||
"ref": {
|
||||
"name": "username",
|
||||
},
|
||||
"type": "",
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`standardSchemaResolver > should return a single error from standardSchemaResolver when validation fails 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"accessToken": {
|
||||
"message": "Invalid input",
|
||||
"ref": undefined,
|
||||
"type": "",
|
||||
},
|
||||
"birthYear": {
|
||||
"message": "Expected number, received string",
|
||||
"ref": undefined,
|
||||
"type": "",
|
||||
},
|
||||
"dateStr": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "",
|
||||
},
|
||||
"email": {
|
||||
"message": "Invalid email",
|
||||
"ref": {
|
||||
"name": "email",
|
||||
},
|
||||
"type": "",
|
||||
},
|
||||
"enabled": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "",
|
||||
},
|
||||
"like": [
|
||||
{
|
||||
"id": {
|
||||
"message": "Expected number, received string",
|
||||
"ref": undefined,
|
||||
"type": "",
|
||||
},
|
||||
"name": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "",
|
||||
},
|
||||
},
|
||||
],
|
||||
"password": {
|
||||
"message": "One uppercase character",
|
||||
"ref": {
|
||||
"name": "password",
|
||||
},
|
||||
"type": "",
|
||||
},
|
||||
"repeatPassword": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "",
|
||||
},
|
||||
"tags": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "",
|
||||
},
|
||||
"url": {
|
||||
"message": "Custom error url",
|
||||
"ref": undefined,
|
||||
"type": "",
|
||||
},
|
||||
"username": {
|
||||
"message": "Required",
|
||||
"ref": {
|
||||
"name": "username",
|
||||
},
|
||||
"type": "",
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`standardSchemaResolver > should return all the errors from standardSchemaResolver when validation fails with \`validateAllFieldCriteria\` set to true 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"accessToken": {
|
||||
"message": "Invalid input",
|
||||
"ref": undefined,
|
||||
"type": "",
|
||||
"types": {
|
||||
"0": "Invalid input",
|
||||
},
|
||||
},
|
||||
"birthYear": {
|
||||
"message": "Expected number, received string",
|
||||
"ref": undefined,
|
||||
"type": "",
|
||||
"types": {
|
||||
"0": "Expected number, received string",
|
||||
},
|
||||
},
|
||||
"dateStr": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "",
|
||||
"types": {
|
||||
"0": "Required",
|
||||
},
|
||||
},
|
||||
"email": {
|
||||
"message": "Invalid email",
|
||||
"ref": {
|
||||
"name": "email",
|
||||
},
|
||||
"type": "",
|
||||
"types": {
|
||||
"0": "Invalid email",
|
||||
},
|
||||
},
|
||||
"enabled": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "",
|
||||
"types": {
|
||||
"0": "Required",
|
||||
},
|
||||
},
|
||||
"like": [
|
||||
{
|
||||
"id": {
|
||||
"message": "Expected number, received string",
|
||||
"ref": undefined,
|
||||
"type": "",
|
||||
"types": {
|
||||
"0": "Expected number, received string",
|
||||
},
|
||||
},
|
||||
"name": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "",
|
||||
"types": {
|
||||
"0": "Required",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
"password": {
|
||||
"message": "One uppercase character",
|
||||
"ref": {
|
||||
"name": "password",
|
||||
},
|
||||
"type": "",
|
||||
"types": {
|
||||
"0": "One uppercase character",
|
||||
"1": "One lowercase character",
|
||||
"2": "One number",
|
||||
"3": "Must be at least 8 characters in length",
|
||||
},
|
||||
},
|
||||
"repeatPassword": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "",
|
||||
"types": {
|
||||
"0": "Required",
|
||||
},
|
||||
},
|
||||
"tags": {
|
||||
"message": "Required",
|
||||
"ref": undefined,
|
||||
"type": "",
|
||||
"types": {
|
||||
"0": "Required",
|
||||
},
|
||||
},
|
||||
"url": {
|
||||
"message": "Custom error url",
|
||||
"ref": undefined,
|
||||
"type": "",
|
||||
"types": {
|
||||
"0": "Custom error url",
|
||||
},
|
||||
},
|
||||
"username": {
|
||||
"message": "Required",
|
||||
"ref": {
|
||||
"name": "username",
|
||||
},
|
||||
"type": "",
|
||||
"types": {
|
||||
"0": "Required",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`standardSchemaResolver > should return values from standardSchemaResolver when validation pass & raw=true 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",
|
||||
},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`standardSchemaResolver > should return values from standardSchemaResolver 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",
|
||||
},
|
||||
}
|
||||
`;
|
||||
151
node_modules/@hookform/resolvers/standard-schema/src/__tests__/standard-schema.ts
generated
vendored
Normal file
151
node_modules/@hookform/resolvers/standard-schema/src/__tests__/standard-schema.ts
generated
vendored
Normal file
@@ -0,0 +1,151 @@
|
||||
import { Resolver, SubmitHandler, useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
import { standardSchemaResolver } from '..';
|
||||
import {
|
||||
customSchema,
|
||||
fields,
|
||||
invalidData,
|
||||
schema,
|
||||
validData,
|
||||
} from './__fixtures__/data';
|
||||
|
||||
const shouldUseNativeValidation = false;
|
||||
|
||||
describe('standardSchemaResolver', () => {
|
||||
it('should return values from standardSchemaResolver when validation pass', async () => {
|
||||
const result = await standardSchemaResolver(schema)(validData, undefined, {
|
||||
fields,
|
||||
shouldUseNativeValidation,
|
||||
});
|
||||
|
||||
expect(result).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return a single error from standardSchemaResolver when validation fails', async () => {
|
||||
const result = await standardSchemaResolver(schema)(
|
||||
invalidData,
|
||||
undefined,
|
||||
{
|
||||
fields,
|
||||
shouldUseNativeValidation,
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return all the errors from standardSchemaResolver when validation fails with `validateAllFieldCriteria` set to true', async () => {
|
||||
const result = await standardSchemaResolver(schema)(
|
||||
invalidData,
|
||||
undefined,
|
||||
{
|
||||
fields,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return values from standardSchemaResolver when validation pass & raw=true', async () => {
|
||||
const validateSpy = vi.spyOn(schema['~standard'], 'validate');
|
||||
|
||||
const result = await standardSchemaResolver(schema, undefined, {
|
||||
raw: true,
|
||||
})(validData, undefined, {
|
||||
fields,
|
||||
shouldUseNativeValidation,
|
||||
});
|
||||
|
||||
expect(validateSpy).toHaveBeenCalledTimes(1);
|
||||
expect(result).toMatchSnapshot();
|
||||
});
|
||||
it('should correctly handle path segments that are objects', async () => {
|
||||
const result = await standardSchemaResolver(customSchema)(
|
||||
validData,
|
||||
undefined,
|
||||
{
|
||||
fields,
|
||||
shouldUseNativeValidation,
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toMatchSnapshot();
|
||||
});
|
||||
|
||||
/**
|
||||
* Type inference tests
|
||||
*/
|
||||
it('should correctly infer the output type from a standardSchema schema', () => {
|
||||
const resolver = standardSchemaResolver(z.object({ id: z.number() }));
|
||||
|
||||
expectTypeOf(resolver).toEqualTypeOf<
|
||||
Resolver<{ id: number }, unknown, { id: number }>
|
||||
>();
|
||||
});
|
||||
|
||||
it('should correctly infer the output type from a standardSchema schema using a transform', () => {
|
||||
const resolver = standardSchemaResolver(
|
||||
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 standardSchema schema when a different input type is specified', () => {
|
||||
const schema = z.object({ id: z.number() }).transform(({ id }) => {
|
||||
return { id: String(id) };
|
||||
});
|
||||
|
||||
const resolver = standardSchemaResolver<
|
||||
{ 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 standardSchema schema for the handleSubmit function in useForm', () => {
|
||||
const schema = z.object({ id: z.number() });
|
||||
|
||||
const form = useForm({
|
||||
resolver: standardSchemaResolver(schema),
|
||||
defaultValues: {
|
||||
id: 3,
|
||||
},
|
||||
});
|
||||
|
||||
expectTypeOf(form.watch('id')).toEqualTypeOf<number>();
|
||||
|
||||
expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
|
||||
SubmitHandler<{
|
||||
id: number;
|
||||
}>
|
||||
>();
|
||||
});
|
||||
|
||||
it('should correctly infer the output type from a standardSchema 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: standardSchemaResolver(schema),
|
||||
defaultValues: {
|
||||
id: 3,
|
||||
},
|
||||
});
|
||||
|
||||
expectTypeOf(form.watch('id')).toEqualTypeOf<number>();
|
||||
|
||||
expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
|
||||
SubmitHandler<{
|
||||
id: string;
|
||||
}>
|
||||
>();
|
||||
});
|
||||
});
|
||||
1
node_modules/@hookform/resolvers/standard-schema/src/index.ts
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/standard-schema/src/index.ts
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export * from './standard-schema';
|
||||
115
node_modules/@hookform/resolvers/standard-schema/src/standard-schema.ts
generated
vendored
Normal file
115
node_modules/@hookform/resolvers/standard-schema/src/standard-schema.ts
generated
vendored
Normal file
@@ -0,0 +1,115 @@
|
||||
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
|
||||
import { StandardSchemaV1 } from '@standard-schema/spec';
|
||||
import { getDotPath } from '@standard-schema/utils';
|
||||
import { FieldError, FieldValues, Resolver } from 'react-hook-form';
|
||||
|
||||
function parseErrorSchema(
|
||||
issues: readonly StandardSchemaV1.Issue[],
|
||||
validateAllFieldCriteria: boolean,
|
||||
) {
|
||||
const errors: Record<string, FieldError> = {};
|
||||
|
||||
for (let i = 0; i < issues.length; i++) {
|
||||
const error = issues[i];
|
||||
const path = getDotPath(error);
|
||||
|
||||
if (path) {
|
||||
if (!errors[path]) {
|
||||
errors[path] = { message: error.message, type: '' };
|
||||
}
|
||||
|
||||
if (validateAllFieldCriteria) {
|
||||
const types = errors[path].types || {};
|
||||
|
||||
errors[path].types = {
|
||||
...types,
|
||||
[Object.keys(types).length]: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
export function standardSchemaResolver<
|
||||
Input extends FieldValues,
|
||||
Context,
|
||||
Output,
|
||||
>(
|
||||
schema: StandardSchemaV1<Input, Output>,
|
||||
_schemaOptions?: never,
|
||||
resolverOptions?: {
|
||||
raw?: false;
|
||||
},
|
||||
): Resolver<Input, Context, Output>;
|
||||
|
||||
export function standardSchemaResolver<
|
||||
Input extends FieldValues,
|
||||
Context,
|
||||
Output,
|
||||
>(
|
||||
schema: StandardSchemaV1<Input, Output>,
|
||||
_schemaOptions: never | undefined,
|
||||
resolverOptions: {
|
||||
raw: true;
|
||||
},
|
||||
): Resolver<Input, Context, Input>;
|
||||
|
||||
/**
|
||||
* Creates a resolver for react-hook-form that validates data using a Standard Schema.
|
||||
*
|
||||
* @param {Schema} schema - The Standard Schema to validate against
|
||||
* @param {Object} resolverOptions - Options for the resolver
|
||||
* @param {boolean} [resolverOptions.raw=false] - Whether to return raw input values instead of parsed values
|
||||
* @returns {Resolver} A resolver function compatible with react-hook-form
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const schema = z.object({
|
||||
* name: z.string().min(2),
|
||||
* age: z.number().min(18)
|
||||
* });
|
||||
*
|
||||
* useForm({
|
||||
* resolver: standardSchemaResolver(schema)
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function standardSchemaResolver<
|
||||
Input extends FieldValues,
|
||||
Context,
|
||||
Output,
|
||||
>(
|
||||
schema: StandardSchemaV1<Input, Output>,
|
||||
_schemaOptions?: never,
|
||||
resolverOptions: {
|
||||
raw?: boolean;
|
||||
} = {},
|
||||
): Resolver<Input, Context, Output | Input> {
|
||||
return async (values, _, options) => {
|
||||
let result = schema['~standard'].validate(values);
|
||||
if (result instanceof Promise) {
|
||||
result = await result;
|
||||
}
|
||||
|
||||
if (result.issues) {
|
||||
const errors = parseErrorSchema(
|
||||
result.issues,
|
||||
!options.shouldUseNativeValidation && options.criteriaMode === 'all',
|
||||
);
|
||||
|
||||
return {
|
||||
values: {},
|
||||
errors: toNestErrors(errors, options),
|
||||
};
|
||||
}
|
||||
|
||||
options.shouldUseNativeValidation && validateFieldsNatively({}, options);
|
||||
|
||||
return {
|
||||
values: resolverOptions.raw ? Object.assign({}, values) : result.value,
|
||||
errors: {},
|
||||
};
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user