Skip to content
Merged
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
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,16 +85,16 @@ import { struct } from "superstruct";

const schema = struct({
name: "string",
age: "number"
age: "number",
});

const App = () => {
const { register, handleSubmit } = useForm({
resolver: superstructResolver(schema)
resolver: superstructResolver(schema),
});

return (
<form onSubmit={handleSubmit(d => console.log(d))}>
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input name="name" ref={register} />
<input name="age" type="number" ref={register} />

Expand All @@ -117,16 +117,16 @@ import { joiResolver } from "@hookform/resolvers";
import Joi from "@hapi/joi";

const schema = Joi.object({
username: Joi.string().required()
username: Joi.string().required(),
});

const App = () => {
const { register, handleSubmit } = useForm({
resolver: joiResolver(schema)
resolver: joiResolver(schema),
});

return (
<form onSubmit={handleSubmit(d => console.log(d))}>
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input name="name" ref={register} />
<input name="age" type="number" ref={register} />

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@hookform/resolvers",
"version": "0.0.3",
"version": "0.0.4",
"description": "React Hook Form validation resolvers: Yup, Joi, Superstruct and etc.",
"main": "dist/index.js",
"module": "dist/index.esm.js",
Expand Down
41 changes: 17 additions & 24 deletions src/joi.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,14 @@
import { appendErrors, transformToNestObject } from 'react-hook-form';
import { appendErrors, transformToNestObject, Resolver } from 'react-hook-form';
import Joi from '@hapi/joi';
import convertArrayToPathName from './utils/convertArrayToPathName';

type JoiError = {
details: any;
};

type FieldValues = Record<string, any>;

type FieldError = {
path: (string | number)[];
message: string;
type: string;
};

const parseErrorSchema = (error: JoiError, validateAllFieldCriteria: boolean) =>
const parseErrorSchema = (
error: Joi.ValidationError,
validateAllFieldCriteria: boolean,
) =>
Array.isArray(error.details)
? error.details.reduce(
(previous: FieldValues, { path, message = '', type }: FieldError) => {
(previous: Record<string, any>, { path, message = '', type }) => {
const currentPath = convertArrayToPathName(path);

return {
Expand Down Expand Up @@ -51,19 +42,21 @@ const parseErrorSchema = (error: JoiError, validateAllFieldCriteria: boolean) =>
)
: [];

export const joiResolver = (
validationSchema: Joi.Schema,
config: any = {
export const joiResolver = <TFieldValues extends Record<string, any>>(
schema: Joi.Schema,
options: Joi.AsyncValidationOptions = {
abortEarly: false,
},
) => async (data: any, _: any = {}, validateAllFieldCriteria = false) => {
): Resolver<TFieldValues> => async (
values,
_,
validateAllFieldCriteria = false,
) => {
try {
const values = await validationSchema.validateAsync(data, {
...config,
});

return {
values,
values: await schema.validateAsync(values, {
...options,
}),
errors: {},
};
} catch (e) {
Expand Down
33 changes: 12 additions & 21 deletions src/superstruct.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,14 @@
import { appendErrors, transformToNestObject } from 'react-hook-form';
import { appendErrors, transformToNestObject, Resolver } from 'react-hook-form';
import Superstruct from 'superstruct';
import convertArrayToPathName from './utils/convertArrayToPathName';

type SuperStructError = {
failures: any;
};

type FieldValues = Record<string, any>;

type FieldError = {
path: (string | number)[];
message: string;
type: string;
};

const parseErrorSchema = (
error: SuperStructError,
error: Superstruct.StructError,
validateAllFieldCriteria: boolean,
) =>
Array.isArray(error.failures)
? error.failures.reduce(
(previous: FieldValues, { path, message = '', type }: FieldError) => {
(previous: Record<string, any>, { path, message = '', type }) => {
const currentPath = convertArrayToPathName(path);

return {
Expand All @@ -31,7 +20,7 @@ const parseErrorSchema = (
currentPath,
validateAllFieldCriteria,
previous,
type,
type || '',
message,
),
}
Expand All @@ -41,7 +30,7 @@ const parseErrorSchema = (
type,
...(validateAllFieldCriteria
? {
types: { [type]: message || true },
types: { [type || '']: message || true },
}
: {}),
},
Expand All @@ -53,14 +42,16 @@ const parseErrorSchema = (
)
: [];

export const superstructResolver = (validationSchema: any) => async (
data: any,
_: any = {},
export const superstructResolver = <TFieldValues extends Record<string, any>>(
schema: Superstruct.Struct,
): Resolver<TFieldValues> => async (
values,
_,
validateAllFieldCriteria = false,
) => {
try {
return {
values: validationSchema(data),
values: schema(values),
errors: {},
};
} catch (e) {
Expand Down
6 changes: 3 additions & 3 deletions src/yup.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,15 +96,15 @@ describe('validateWithSchema', () => {
validate: () => {
throw errors;
},
})({}),
} as any)({}),
).toMatchSnapshot();
});

it('should return empty object when validate pass', async () => {
expect(
await yupResolver({
validate: () => new Promise((resolve) => resolve()) as any,
})({}),
validate: () => new Promise((resolve) => resolve()),
} as any)({}),
).toEqual({
errors: {},
values: undefined,
Expand Down
34 changes: 15 additions & 19 deletions src/yup.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,13 @@
import { appendErrors, transformToNestObject } from 'react-hook-form';

type YupValidationError = {
inner: { path: string; message: string; type: string }[];
path: string;
message: string;
type: string;
};

type FieldValues = Record<string, any>;
import { appendErrors, transformToNestObject, Resolver } from 'react-hook-form';
import Yup from 'yup';

const parseErrorSchema = (
error: YupValidationError,
error: Yup.ValidationError,
validateAllFieldCriteria: boolean,
) =>
Array.isArray(error.inner)
? error.inner.reduce(
(previous: FieldValues, { path, message, type }: FieldValues) => ({
(previous: Record<string, any>, { path, message, type }) => ({
...previous,
...(path
? previous[path] && validateAllFieldCriteria
Expand Down Expand Up @@ -47,17 +39,21 @@ const parseErrorSchema = (
[error.path]: { message: error.message, type: error.type },
};

export const yupResolver = (
validationSchema: any,
config: any = {
export const yupResolver = <TFieldValues extends Record<string, any>>(
schema: Yup.ObjectSchema,
options: Yup.ValidateOptions = {
abortEarly: false,
},
) => async (data: any, _: any = {}, validateAllFieldCriteria = false) => {
): Resolver<TFieldValues> => async (
values,
_,
validateAllFieldCriteria = false,
) => {
try {
return {
values: await validationSchema.validate(data, {
...config,
}),
values: (await schema.validate(values, {
...options,
})) as any,
errors: {},
};
} catch (e) {
Expand Down