From 87e1877649224ee782c6a4f55b55ec1a65e5a3ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BA=8C=E8=B4=A7=E7=88=B1=E5=90=83=E7=99=BD=E8=90=9D?= =?UTF-8?q?=E5=8D=9C?= Date: Wed, 14 Aug 2024 11:20:55 +0800 Subject: [PATCH] Fix replaceMessage function to handle escaped variables (#716) * Fix replaceMessage function to handle escaped variables Modify the `replaceMessage` function in `src/utils/validateUtil.ts` to handle escaped variables and add related test cases. * **replaceMessage function**: - Update the `replaceMessage` function to skip conversion when `\${xxx}` is passed and convert `${xxx}` correctly. - Check for the presence of `\${xxx}` and skip conversion in such cases. - Ensure the function correctly converts `${xxx}` to the corresponding value from the `kv` object. * **validate.test.tsx**: - Add test cases to verify the correct handling of `\${xxx}` and `${xxx}`. - Ensure the test cases cover both scenarios: skipping conversion and converting correctly. - Add a new test case to handle escaped and unescaped variables correctly. --- For more details, open the [Copilot Workspace session](https://copilot-workspace.githubnext.com/react-component/field-form?shareId=XXXX-XXXX-XXXX-XXXX). * Update validateUtil.ts * test: fix test case --- src/utils/validateUtil.ts | 5 ++++- tests/validate.test.tsx | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/utils/validateUtil.ts b/src/utils/validateUtil.ts index d6b4146ed..09106d1d2 100644 --- a/src/utils/validateUtil.ts +++ b/src/utils/validateUtil.ts @@ -19,7 +19,10 @@ const AsyncValidator: any = RawAsyncValidator; * `I'm ${name}` + { name: 'bamboo' } = I'm bamboo */ function replaceMessage(template: string, kv: Record): string { - return template.replace(/\$\{\w+\}/g, (str: string) => { + return template.replace(/\\?\$\{\w+\}/g, (str: string) => { + if (str.startsWith('\\')) { + return str.slice(1); + } const key = str.slice(2, -1); return kv[key]; }); diff --git a/tests/validate.test.tsx b/tests/validate.test.tsx index e5810d775..2a9d92271 100644 --- a/tests/validate.test.tsx +++ b/tests/validate.test.tsx @@ -1081,4 +1081,28 @@ describe('Form.Validate', () => { jest.useRealTimers(); }); + + it('should handle escaped and unescaped variables correctly', async () => { + const { container } = render( +
+ Promise.reject(new Error('\\${name} should be ${name}!')), + }, + ]} + > + + +
, + ); + + // Wrong value + await changeValue(getInput(container), 'light'); + matchError(container, '${name} should be bamboo!'); + }); });