Skip to content

Commit 8befb5e

Browse files
fix: fix nesting issue due to the errors order
1 parent e95721d commit 8befb5e

File tree

3 files changed

+23
-8
lines changed

3 files changed

+23
-8
lines changed

src/__tests__/__snapshots__/toNestErrors.ts.snap

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@
33
exports[`transforms flat object to nested object 1`] = `
44
{
55
"name": {
6+
"firstName": {
7+
"message": "third message",
8+
"ref": undefined,
9+
"type": "rd",
10+
},
611
"message": "first message",
712
"ref": {
813
"reportValidity": [MockFunction spy],
@@ -25,6 +30,11 @@ exports[`transforms flat object to nested object 1`] = `
2530
exports[`transforms flat object to nested object and shouldUseNativeValidation: true 1`] = `
2631
{
2732
"name": {
33+
"firstName": {
34+
"message": "third message",
35+
"ref": undefined,
36+
"type": "rd",
37+
},
2838
"message": "first message",
2939
"ref": {
3040
"reportValidity": [MockFunction spy] {

src/__tests__/toNestErrors.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { toNestErrors } from '../toNestErrors';
33

44
const flatObject: Record<string, FieldError> = {
55
name: { type: 'st', message: 'first message' },
6+
'name.firstName': { type: 'rd', message: 'third message' },
67
'test.0.name': { type: 'nd', message: 'second message' },
78
};
89

src/toNestErrors.ts

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,24 +14,28 @@ export const toNestErrors = <TFieldValues extends FieldValues>(
1414
options: ResolverOptions<TFieldValues>,
1515
): FieldErrors<TFieldValues> => {
1616
options.shouldUseNativeValidation && validateFieldsNatively(errors, options);
17-
1817
const fieldErrors = {} as FieldErrors<TFieldValues>;
1918
for (const path in errors) {
2019
const field = get(options.fields, path) as Field['_f'] | undefined;
21-
const error = Object.assign(errors[path] || {}, {
22-
ref: field && field.ref,
23-
});
24-
2520
if (isNameInFieldArray(options.names || Object.keys(errors), path)) {
26-
const fieldArrayErrors = Object.assign({}, get(fieldErrors, path));
27-
21+
const fieldArrayErrors = Object.assign(
22+
{},
23+
structuredClone(get(fieldErrors, path)),
24+
);
25+
const error = Object.assign(structuredClone(errors[path]) || {}, {
26+
ref: field && field.ref,
27+
});
2828
set(fieldArrayErrors, 'root', error);
2929
set(fieldErrors, path, fieldArrayErrors);
3030
} else {
31+
const error = Object.assign(
32+
structuredClone(errors[path]) || {},
33+
structuredClone(get(fieldErrors, path)),
34+
{ ref: field && field.ref },
35+
);
3136
set(fieldErrors, path, error);
3237
}
3338
}
34-
3539
return fieldErrors;
3640
};
3741

0 commit comments

Comments
 (0)