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
21 changes: 21 additions & 0 deletions src/__tests__/toNestErrors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -284,3 +284,24 @@ test('ensures consistent ordering when a field array has a root error and an err
},
});
});

test('should correctly validate object with special characters', () => {
const result = toNestErrors(
{ '[array-2]': { type: 'string', message: 'string is required' } },
{
names: ['[array-2]'],
fields: {
'[array-2]': { name: '[array-2]', ref: { name: '[array-2]' } },
},
shouldUseNativeValidation: false,
},
);

expect(result).toEqual({
'array-2': {
type: 'string',
message: 'string is required',
ref: { name: '[array-2]' },
},
});
});
16 changes: 15 additions & 1 deletion src/toNestErrors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,18 @@ export const toNestErrors = <TFieldValues extends FieldValues>(
const isNameInFieldArray = (
names: InternalFieldName[],
name: InternalFieldName,
) => names.some((n) => n.match(`^${name}\\.\\d+`));
) => {
const path = escapeBrackets(name);
return names.some((n) => escapeBrackets(n).match(`^${path}\\.\\d+`));
};

/**
* Escapes special characters in a string to be used in a regex pattern.
* it removes the brackets from the string to match the `set` method.
*
* @param input - The input string to escape.
* @returns The escaped string.
*/
function escapeBrackets(input: string): string {
return input.replace(/\]|\[/g, '');
}