Skip to content
Open
Show file tree
Hide file tree
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
10 changes: 10 additions & 0 deletions src/__tests__/__snapshots__/toNestErrors.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
exports[`transforms flat object to nested object 1`] = `
{
"name": {
"firstName": {
"message": "third message",
"ref": undefined,
"type": "rd",
},
"message": "first message",
"ref": {
"reportValidity": [MockFunction spy],
Expand All @@ -25,6 +30,11 @@ exports[`transforms flat object to nested object 1`] = `
exports[`transforms flat object to nested object and shouldUseNativeValidation: true 1`] = `
{
"name": {
"firstName": {
"message": "third message",
"ref": undefined,
"type": "rd",
},
"message": "first message",
"ref": {
"reportValidity": [MockFunction spy] {
Expand Down
1 change: 1 addition & 0 deletions src/__tests__/toNestErrors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { toNestErrors } from '../toNestErrors';

const flatObject: Record<string, FieldError> = {
name: { type: 'st', message: 'first message' },
'name.firstName': { type: 'rd', message: 'third message' },
'test.0.name': { type: 'nd', message: 'second message' },
};

Expand Down
20 changes: 12 additions & 8 deletions src/toNestErrors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,24 +14,28 @@ export const toNestErrors = <TFieldValues extends FieldValues>(
options: ResolverOptions<TFieldValues>,
): FieldErrors<TFieldValues> => {
options.shouldUseNativeValidation && validateFieldsNatively(errors, options);

const fieldErrors = {} as FieldErrors<TFieldValues>;
for (const path in errors) {
const field = get(options.fields, path) as Field['_f'] | undefined;
const error = Object.assign(errors[path] || {}, {
ref: field && field.ref,
});

if (isNameInFieldArray(options.names || Object.keys(errors), path)) {
const fieldArrayErrors = Object.assign({}, get(fieldErrors, path));

const fieldArrayErrors = Object.assign(
{},
structuredClone(get(fieldErrors, path)),
);
const error = Object.assign(structuredClone(errors[path]) || {}, {
ref: field && field.ref,
});
set(fieldArrayErrors, 'root', error);
set(fieldErrors, path, fieldArrayErrors);
} else {
const error = Object.assign(
structuredClone(errors[path]) || {},
structuredClone(get(fieldErrors, path)),
{ ref: field && field.ref },
);
set(fieldErrors, path, error);
}
}

return fieldErrors;
};

Expand Down