-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
valiForm.ts
31 lines (30 loc) · 883 Bytes
/
valiForm.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import type { BaseSchema, BaseSchemaAsync } from 'valibot';
import type {
FieldValues,
ValidateForm,
PartialValues,
FormErrors,
} from '../types';
/**
* Creates a validation functions that parses the Valibot schema of a form.
*
* @param schema A Valibot schema.
*
* @returns A validation function.
*/
export function valiForm<TFieldValues extends FieldValues>(
schema: BaseSchema<TFieldValues, any> | BaseSchemaAsync<TFieldValues, any>
): ValidateForm<TFieldValues> {
return async (values: PartialValues<TFieldValues>) => {
const result = await schema._parse(values, { abortPipeEarly: true });
return result.issues
? result.issues.reduce<FormErrors<TFieldValues>>(
(errors, issue) => ({
...errors,
[issue.path!.map(({ key }) => key).join('.')]: issue.message,
}),
{}
)
: {};
};
}