From c633ca3215042f0bf561c35cecd2f99fd95af54b Mon Sep 17 00:00:00 2001 From: Yoann Fleury Date: Thu, 25 Jul 2024 13:57:36 +0200 Subject: [PATCH] feat: add getFieldPath a function that helps with path name typings --- src/lib/form/getFieldPath.ts | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/lib/form/getFieldPath.ts diff --git a/src/lib/form/getFieldPath.ts b/src/lib/form/getFieldPath.ts new file mode 100644 index 000000000..a11320001 --- /dev/null +++ b/src/lib/form/getFieldPath.ts @@ -0,0 +1,31 @@ +import { FieldPath, FieldValues } from 'react-hook-form'; + +/** + * Use this function to build a path for a form. This function will type check + * the name to make sure you don't have typo or inexistant field path. + * + * Example: + * ``` + * const zPasswordForm = () => z.object({ currentPassword: z.string(), newPassword: z.string() }); + * type PasswordForm = z.infer>; + * + * zPasswordForm() + * .superRefine((obj, ctx) => { + * if (obj.currentPassword === obj.newPassword) { + * ctx.addIssue({ + * code: z.ZodIssueCode.custom, + * path: getFieldPath('currentPassword'), // typed checked + * message: 'The password should not be the same', + * }); + * } + * }) + * + * ``` + * @param name The name that will be type checked and split. + * @returns The array made from the name (splitted on '.') + */ +export function getFieldPath( + name: FieldPath +) { + return name.split('.'); +}