diff --git a/src/__tests__/toNestErrors.ts b/src/__tests__/toNestErrors.ts index 6ac0df66..983fdded 100644 --- a/src/__tests__/toNestErrors.ts +++ b/src/__tests__/toNestErrors.ts @@ -204,3 +204,54 @@ test('transforms flat object to nested object with root error for field array', ], }); }); + +test('ensures consistent ordering when a field array has a root error and an error in the non-first element', () => { + const result = toNestErrors( + { + 'fieldArrayWithRootError.1.name': { + type: 'second', + message: 'second message', + }, + fieldArrayWithRootError: { type: 'root-error', message: 'root message' }, + }, + { + fields: { + fieldArrayWithRootError: { + name: 'fieldArrayWithRootError', + ref: { name: 'fieldArrayWithRootError' }, + }, + 'fieldArrayWithRootError.0.name': { + name: 'fieldArrayWithRootError.0.name', + ref: { name: 'fieldArrayWithRootError.0.name' }, + }, + 'fieldArrayWithRootError.1.name': { + name: 'fieldArrayWithRootError.1.name', + ref: { name: 'fieldArrayWithRootError.1.name' }, + }, + }, + names: [ + 'fieldArrayWithRootError', + 'fieldArrayWithRootError.0.name', + 'fieldArrayWithRootError.1.name', + ], + shouldUseNativeValidation: false, + }, + ); + + expect(result).toEqual({ + fieldArrayWithRootError: { + '1': { + name: { + type: 'second', + message: 'second message', + ref: { name: 'fieldArrayWithRootError.1.name' }, + }, + }, + root: { + type: 'root-error', + message: 'root message', + ref: { name: 'fieldArrayWithRootError' }, + }, + }, + }); +}); diff --git a/src/toNestErrors.ts b/src/toNestErrors.ts index 5c4b839b..e68d3d39 100644 --- a/src/toNestErrors.ts +++ b/src/toNestErrors.ts @@ -23,10 +23,7 @@ export const toNestErrors = ( }); if (isNameInFieldArray(options.names || Object.keys(errors), path)) { - const fieldArrayErrors = Object.assign( - {}, - compact(get(fieldErrors, path)), - ); + const fieldArrayErrors = Object.assign({}, get(fieldErrors, path)); set(fieldArrayErrors, 'root', error); set(fieldErrors, path, fieldArrayErrors); @@ -38,9 +35,6 @@ export const toNestErrors = ( return fieldErrors; }; -const compact = (value: TValue[]) => - Array.isArray(value) ? value.filter(Boolean) : []; - const isNameInFieldArray = ( names: InternalFieldName[], name: InternalFieldName,