Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 47 additions & 1 deletion src/toNestErrors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,55 @@ import {
FieldValues,
InternalFieldName,
} from 'react-hook-form';
import set from 'lodash.set';
import { validateFieldsNatively } from './validateFieldsNatively';

export const isDateObject = (value: unknown): value is Date => value instanceof Date;

export const isNullOrUndefined = (value: unknown): value is null | undefined => value == null;

export const isObjectType = (value: unknown): value is object =>
typeof value === 'object';

export const isObject = <T extends object>(value: unknown): value is T =>
!isNullOrUndefined(value) &&
!Array.isArray(value) &&
isObjectType(value) &&
!isDateObject(value);

export const isKey = (value: string) => /^\w*$/.test(value);

const compact = <TValue>(value: TValue[]) =>
Array.isArray(value) ? value.filter(Boolean) : [];

const stringToPath = (input: string): string[] =>
compact(input.replace(/["|']|\]/g, '').split(/\.|\[/));

const set = (object: FieldValues, path: string, value?: unknown) => {
let index = -1;
const tempPath = isKey(path) ? [path] : stringToPath(path);
const length = tempPath.length;
const lastIndex = length - 1;

while (++index < length) {
const key = tempPath[index];
let newValue = value;

if (index !== lastIndex) {
const objValue = object[key];
newValue =
isObject(objValue) || Array.isArray(objValue)
? objValue
: !isNaN(+tempPath[index + 1])
? []
: {};
}
object[key] = newValue;
object = object[key];
}
return object;
};


export const toNestErrors = <TFieldValues extends FieldValues>(
errors: FieldErrors,
options: ResolverOptions<TFieldValues>,
Expand Down