diff --git a/src/__tests__/toNestErrors.ts b/src/__tests__/toNestErrors.ts index ebea9170..67d493c6 100644 --- a/src/__tests__/toNestErrors.ts +++ b/src/__tests__/toNestErrors.ts @@ -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]' }, + }, + }); +}); diff --git a/src/toNestErrors.ts b/src/toNestErrors.ts index 454f7d45..4bd48b51 100644 --- a/src/toNestErrors.ts +++ b/src/toNestErrors.ts @@ -38,4 +38,18 @@ export const toNestErrors = ( 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, ''); +}