I want to disable the Submit button which is outside of the Antd Form when the fields are not valid. Please help to accomplish this task.
This is my Component Code
const CreateAndEditForm = () => {
const [form] = Form.useForm();
const onSave = (e) => {
form.submit()
}
return (
<>
<PageTitle title="Add New Form">
<Space size="small">
<Button onClick={onSave} type="primary" htmlType="submit"
>
<SaveOutlined /> Save
</Button>
</Space>
</PageTitle>
<Row>
<Col span={24}>
<Form
form={form}
layout="vertical"
name="addForm"
requiredMark={false}
>
<Form.Item
name="name"
label="Name"
rules={[{ required: true, message: 'Please Enter a Name' }]}
>
<Input />
</Form.Item>
<Form.Item name="description" label="Description" rules={[{ required: true, message: 'Please Enter a Description' }]}>
<Input placeholder="Enter Description" />
</Form.Item>
</Form>
</Col>
</Row>
</>
);
}
export default CreateAndEditSchedule;
You can make a check every time something change in the form using onValuesChange
property. Then, a hook will allow you to render the submit button in the right way.
Example:
const [formValid, setFormValid] = useState(true)
<Form
onValuesChange={() => setFormValid(form.getFieldsError().some((item) => item.errors.length > 0) }
/>
<Button
onClick={onSave}
type="primary"
htmlType="submit"
disabled={formValid}
/>