@@ -6,9 +6,55 @@ import {
6
6
FieldValues ,
7
7
InternalFieldName ,
8
8
} from 'react-hook-form' ;
9
- import set from 'lodash.set' ;
10
9
import { validateFieldsNatively } from './validateFieldsNatively' ;
11
10
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
+
12
58
export const toNestErrors = < TFieldValues extends FieldValues > (
13
59
errors : FieldErrors ,
14
60
options : ResolverOptions < TFieldValues > ,
0 commit comments