【问题标题】:antd form item validation fails if default value haven't been changed如果未更改默认值,则 antd 表单项验证失败
【发布时间】:2020-05-01 18:01:13
【问题描述】:

我的 React 组件中有 antd 表单。默认值来自props,我即将在提交时更改redux store。但是,如果用户不更改输入值并按下“保存”,则验证失败并且在控制台日志中我得到了 util.js:19 async-validator: ["'title' is required"]

<Form name="title" onFinish={this.submitEdit} >
    <Form.Item name="title" rules={[{ required: true, message: 'Required field' }]}>
        <Input defaultValue={this.props.title} placeholder="Enter entry title"/>
    </Form.Item>
    <div>
        <Button type="primary" htmlType="submit">Save</Button>
        <Button onClick={this.cancelEdit}>Cancel</Button>
    </div>
</Form>

antd 日历控件也有类似的问题。尝试编写自定义验证器,但看起来如果没有更改,输入值未定义。我有机会让它发挥作用吗?

【问题讨论】:

    标签: reactjs antd


    【解决方案1】:

    是的,根据文档here,您需要在&lt;Form.Item&gt; 上使用initialValue 属性,然后它才能工作。

    <Form name="title" onFinish={this.submitEdit} >
        <Form.Item
          name="title"
          rules={[{ required: true, message: 'Required field' }]} 
          initialValue={this.props.title}
          >
            <Input placeholder="Enter entry title"/>
        </Form.Item>
        <div>
            <Button type="primary" htmlType="submit">Save</Button>
            <Button onClick={this.cancelEdit}>Cancel</Button>
        </div>
    </Form>
    

    干杯。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-26
      • 2014-08-17
      • 2020-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多