Skip to content

Commit 50dd4ad

Browse files
authored
fix: escape square brackets in field name regex pattern (#752)
1 parent ded1746 commit 50dd4ad

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

src/__tests__/toNestErrors.ts

+21
Original file line numberDiff line numberDiff line change
@@ -284,3 +284,24 @@ test('ensures consistent ordering when a field array has a root error and an err
284284
},
285285
});
286286
});
287+
288+
test('should correctly validate object with special characters', () => {
289+
const result = toNestErrors(
290+
{ '[array-2]': { type: 'string', message: 'string is required' } },
291+
{
292+
names: ['[array-2]'],
293+
fields: {
294+
'[array-2]': { name: '[array-2]', ref: { name: '[array-2]' } },
295+
},
296+
shouldUseNativeValidation: false,
297+
},
298+
);
299+
300+
expect(result).toEqual({
301+
'array-2': {
302+
type: 'string',
303+
message: 'string is required',
304+
ref: { name: '[array-2]' },
305+
},
306+
});
307+
});

src/toNestErrors.ts

+15-1
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,18 @@ export const toNestErrors = <TFieldValues extends FieldValues>(
3838
const isNameInFieldArray = (
3939
names: InternalFieldName[],
4040
name: InternalFieldName,
41-
) => names.some((n) => n.match(`^${name}\\.\\d+`));
41+
) => {
42+
const path = escapeBrackets(name);
43+
return names.some((n) => escapeBrackets(n).match(`^${path}\\.\\d+`));
44+
};
45+
46+
/**
47+
* Escapes special characters in a string to be used in a regex pattern.
48+
* it removes the brackets from the string to match the `set` method.
49+
*
50+
* @param input - The input string to escape.
51+
* @returns The escaped string.
52+
*/
53+
function escapeBrackets(input: string): string {
54+
return input.replace(/\]|\[/g, '');
55+
}

0 commit comments

Comments
 (0)