Skip to content

Commit 87e1877

Browse files
authored
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
1 parent ca2f92c commit 87e1877

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/utils/validateUtil.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,10 @@ const AsyncValidator: any = RawAsyncValidator;
1919
* `I'm ${name}` + { name: 'bamboo' } = I'm bamboo
2020
*/
2121
function replaceMessage(template: string, kv: Record<string, string>): string {
22-
return template.replace(/\$\{\w+\}/g, (str: string) => {
22+
return template.replace(/\\?\$\{\w+\}/g, (str: string) => {
23+
if (str.startsWith('\\')) {
24+
return str.slice(1);
25+
}
2326
const key = str.slice(2, -1);
2427
return kv[key];
2528
});

tests/validate.test.tsx

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1081,4 +1081,28 @@ describe('Form.Validate', () => {
10811081

10821082
jest.useRealTimers();
10831083
});
1084+
1085+
it('should handle escaped and unescaped variables correctly', async () => {
1086+
const { container } = render(
1087+
<Form>
1088+
<InfoField
1089+
messageVariables={{
1090+
name: 'bamboo',
1091+
}}
1092+
name="test"
1093+
rules={[
1094+
{
1095+
validator: () => Promise.reject(new Error('\\${name} should be ${name}!')),
1096+
},
1097+
]}
1098+
>
1099+
<Input />
1100+
</InfoField>
1101+
</Form>,
1102+
);
1103+
1104+
// Wrong value
1105+
await changeValue(getInput(container), 'light');
1106+
matchError(container, '${name} should be bamboo!');
1107+
});
10841108
});

0 commit comments

Comments
 (0)