mirror of
https://gitee.com/ant-design/ant-design.git
synced 2024-12-01 03:29:39 +08:00
fix: required support dynamic updated rules (#20207)
This commit is contained in:
parent
b07d95b0dd
commit
92e5107ef8
@ -149,11 +149,22 @@ const FormItem: React.FC<FormItemProps> = (props: FormItemProps) => {
|
||||
[`${prefixCls}-item-is-validating`]: mergedValidateStatus === 'validating',
|
||||
};
|
||||
|
||||
// TODO: Check if user add `required` in RuleRender
|
||||
const isRequired =
|
||||
required !== undefined
|
||||
? required
|
||||
: !!(rules && rules.some(rule => typeof rule === 'object' && rule.required));
|
||||
: !!(
|
||||
rules &&
|
||||
rules.some(rule => {
|
||||
if (rule && typeof rule === 'object' && rule.required) {
|
||||
return true;
|
||||
}
|
||||
if (typeof rule === 'function') {
|
||||
const ruleEntity = rule(context);
|
||||
return ruleEntity && ruleEntity.required;
|
||||
}
|
||||
return false;
|
||||
})
|
||||
);
|
||||
|
||||
// ======================= Children =======================
|
||||
const fieldId = getFieldId(mergedName, formName);
|
||||
|
@ -207,4 +207,28 @@ describe('Form', () => {
|
||||
'Warning: [antd: Form.Item] `name` is only used for validate React element. If you are using Form.Item as layout display, please remove `name` instead.',
|
||||
);
|
||||
});
|
||||
|
||||
it('dynamic change required', () => {
|
||||
const wrapper = mount(
|
||||
<Form>
|
||||
<Form.Item label="light" name="light" valuePropName="checked">
|
||||
<input type="checkbox" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
label="bamboo"
|
||||
name="bamboo"
|
||||
dependencies={['light']}
|
||||
rules={[({ getFieldValue }) => ({ required: getFieldValue('light') })]}
|
||||
>
|
||||
<input />
|
||||
</Form.Item>
|
||||
</Form>,
|
||||
);
|
||||
|
||||
expect(wrapper.find('.ant-form-item-required')).toHaveLength(0);
|
||||
|
||||
wrapper.find('input[type="checkbox"]').simulate('change', { target: { checked: true } });
|
||||
wrapper.update();
|
||||
expect(wrapper.find('.ant-form-item-required')).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
@ -236,6 +236,12 @@ validateFields()
|
||||
|
||||
#### Rule
|
||||
|
||||
Rule support config object, an also support function to get config object:
|
||||
|
||||
```tsx
|
||||
type Rule = RuleConfig | ((form: FormInstance) => RuleConfig);
|
||||
```
|
||||
|
||||
| Name | Description | Type |
|
||||
| --- | --- | --- |
|
||||
| enum | Match enum value | any[] |
|
||||
|
@ -237,6 +237,12 @@ validateFields()
|
||||
|
||||
#### Rule
|
||||
|
||||
Rule 支持接收 object 进行配置,也支持 function 来动态获取 from 的数据:
|
||||
|
||||
```tsx
|
||||
type Rule = RuleConfig | ((form: FormInstance) => RuleConfig);
|
||||
```
|
||||
|
||||
| 名称 | 说明 | 类型 |
|
||||
| --- | --- | --- |
|
||||
| enum | 是否匹配枚举中的值 | any[] |
|
||||
|
Loading…
Reference in New Issue
Block a user