1- import { FieldValues } from 'react-hook-form' ;
1+ import { FieldValues , useForm } from 'react-hook-form' ;
22
33/**
44 * Convert a simple validation function that returns an object matching the form shape with errors
55 * to a validation resolver compatible with react-hook-form.
66 *
77 * @example
8- * const validate = (values: any ) => {
8+ * const validate = (values: { username: string } ) => {
99 * if (values.username == null || values.username.trim() === '') {
1010 * return { username: 'Required' };
1111 * }
12- * }
12+ * };
1313 *
1414 * const validationResolver = getSimpleValidationResolver(validate);
1515 *
@@ -23,12 +23,15 @@ import { FieldValues } from 'react-hook-form';
2323 * );
2424 */
2525export const getSimpleValidationResolver =
26- ( validate : ValidateForm ) => async ( data : FieldValues ) => {
26+ < TFieldValues extends FieldValues = FieldValues > (
27+ validate : ValidateForm < TFieldValues >
28+ ) =>
29+ async ( data : TFieldValues ) => {
2730 const errors = await validate ( data ) ;
2831
2932 // If there are no errors, early return the form values
3033 if ( ! errors || isEmptyObject ( errors ) ) {
31- return { values : data , errors : { } } ;
34+ return { values : data as TFieldValues , errors : { } } ;
3235 }
3336
3437 // Else, we return an error object shaped like errors but having for each leaf
@@ -40,12 +43,12 @@ export const getSimpleValidationResolver =
4043 // e.g. with an ArrayInput we can get something like: `{backlinks: [{}, {}] }`
4144 // If, after transformation, there are no errors, we return the form values
4245 if ( ! transformedErrors || isEmptyObject ( transformedErrors ) ) {
43- return { values : data , errors : { } } ;
46+ return { values : data as TFieldValues , errors : { } } ;
4447 }
4548
4649 // Else return the errors and no values
4750 return {
48- values : { } ,
51+ values : { } as TFieldValues ,
4952 errors : transformedErrors ,
5053 } ;
5154 } ;
@@ -103,6 +106,9 @@ const isRaTranslationObj = (obj: object) =>
103106const isEmptyObject = ( obj : object ) =>
104107 obj == null || Object . getOwnPropertyNames ( obj ) . length === 0 ;
105108
106- export type ValidateForm = (
107- data : FieldValues
108- ) => FieldValues | Promise < FieldValues > ;
109+ export type ValidateForm < TFieldValues extends FieldValues = FieldValues > = (
110+ data : TFieldValues
111+ ) =>
112+ | Partial < Record < keyof TFieldValues , any > >
113+ | undefined
114+ | Promise < Partial < Record < keyof TFieldValues , any > > > ;
0 commit comments