@@ -6,9 +6,55 @@ import {
66 FieldValues ,
77 InternalFieldName ,
88} from 'react-hook-form' ;
9- import set from 'lodash.set' ;
109import { validateFieldsNatively } from './validateFieldsNatively' ;
1110
11+ export const isDateObject = ( value : unknown ) : value is Date => value instanceof Date ;
12+
13+ export const isNullOrUndefined = ( value : unknown ) : value is null | undefined => value == null ;
14+
15+ export const isObjectType = ( value : unknown ) : value is object =>
16+ typeof value === 'object' ;
17+
18+ export const isObject = < T extends object > ( value : unknown ) : value is T =>
19+ ! isNullOrUndefined ( value ) &&
20+ ! Array . isArray ( value ) &&
21+ isObjectType ( value ) &&
22+ ! isDateObject ( value ) ;
23+
24+ export const isKey = ( value : string ) => / ^ \w * $ / . test ( value ) ;
25+
26+ const compact = < TValue > ( value : TValue [ ] ) =>
27+ Array . isArray ( value ) ? value . filter ( Boolean ) : [ ] ;
28+
29+ const stringToPath = ( input : string ) : string [ ] =>
30+ compact ( input . replace ( / [ " | ' ] | \] / g, '' ) . split ( / \. | \[ / ) ) ;
31+
32+ const set = ( object : FieldValues , path : string , value ?: unknown ) => {
33+ let index = - 1 ;
34+ const tempPath = isKey ( path ) ? [ path ] : stringToPath ( path ) ;
35+ const length = tempPath . length ;
36+ const lastIndex = length - 1 ;
37+
38+ while ( ++ index < length ) {
39+ const key = tempPath [ index ] ;
40+ let newValue = value ;
41+
42+ if ( index !== lastIndex ) {
43+ const objValue = object [ key ] ;
44+ newValue =
45+ isObject ( objValue ) || Array . isArray ( objValue )
46+ ? objValue
47+ : ! isNaN ( + tempPath [ index + 1 ] )
48+ ? [ ]
49+ : { } ;
50+ }
51+ object [ key ] = newValue ;
52+ object = object [ key ] ;
53+ }
54+ return object ;
55+ } ;
56+
57+
1258export const toNestErrors = < TFieldValues extends FieldValues > (
1359 errors : FieldErrors ,
1460 options : ResolverOptions < TFieldValues > ,
0 commit comments