Skip to content

Commit

Permalink
Fix replaceMessage function to handle escaped variables (#716)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
zombieJ authored Aug 14, 2024
1 parent ca2f92c commit 87e1877
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/utils/validateUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ const AsyncValidator: any = RawAsyncValidator;
* `I'm ${name}` + { name: 'bamboo' } = I'm bamboo
*/
function replaceMessage(template: string, kv: Record<string, string>): 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];
});
Expand Down
24 changes: 24 additions & 0 deletions tests/validate.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1081,4 +1081,28 @@ describe('Form.Validate', () => {

jest.useRealTimers();
});

it('should handle escaped and unescaped variables correctly', async () => {
const { container } = render(
<Form>
<InfoField
messageVariables={{
name: 'bamboo',
}}
name="test"
rules={[
{
validator: () => Promise.reject(new Error('\\${name} should be ${name}!')),
},
]}
>
<Input />
</InfoField>
</Form>,
);

// Wrong value
await changeValue(getInput(container), 'light');
matchError(container, '${name} should be bamboo!');
});
});

0 comments on commit 87e1877

Please sign in to comment.