From 8befb5e630a63515c95321baeccf89d0c6e11676 Mon Sep 17 00:00:00 2001 From: Volodymyr Kushnir Date: Wed, 22 Oct 2025 21:06:49 +0200 Subject: [PATCH] fix: fix nesting issue due to the errors order --- .../__snapshots__/toNestErrors.ts.snap | 10 ++++++++++ src/__tests__/toNestErrors.ts | 1 + src/toNestErrors.ts | 20 +++++++++++-------- 3 files changed, 23 insertions(+), 8 deletions(-) diff --git a/src/__tests__/__snapshots__/toNestErrors.ts.snap b/src/__tests__/__snapshots__/toNestErrors.ts.snap index d58e0527..ee0c1a16 100644 --- a/src/__tests__/__snapshots__/toNestErrors.ts.snap +++ b/src/__tests__/__snapshots__/toNestErrors.ts.snap @@ -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], @@ -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] { diff --git a/src/__tests__/toNestErrors.ts b/src/__tests__/toNestErrors.ts index 67d493c6..70648cec 100644 --- a/src/__tests__/toNestErrors.ts +++ b/src/__tests__/toNestErrors.ts @@ -3,6 +3,7 @@ import { toNestErrors } from '../toNestErrors'; const flatObject: Record = { name: { type: 'st', message: 'first message' }, + 'name.firstName': { type: 'rd', message: 'third message' }, 'test.0.name': { type: 'nd', message: 'second message' }, }; diff --git a/src/toNestErrors.ts b/src/toNestErrors.ts index 4bd48b51..c1d72972 100644 --- a/src/toNestErrors.ts +++ b/src/toNestErrors.ts @@ -14,24 +14,28 @@ export const toNestErrors = ( options: ResolverOptions, ): FieldErrors => { options.shouldUseNativeValidation && validateFieldsNatively(errors, options); - const fieldErrors = {} as FieldErrors; 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; };