Skip to content
Merged
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
51 changes: 51 additions & 0 deletions src/__tests__/toNestErrors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' },
},
},
});
});
8 changes: 1 addition & 7 deletions src/toNestErrors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,7 @@ export const toNestErrors = <TFieldValues extends FieldValues>(
});

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);
Expand All @@ -38,9 +35,6 @@ export const toNestErrors = <TFieldValues extends FieldValues>(
return fieldErrors;
};

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

const isNameInFieldArray = (
names: InternalFieldName[],
name: InternalFieldName,
Expand Down