How could I disable form submit button using antd
Form validations work, but I need to visually disable form submit button when validation fails
This is a stackblitz url https://stackblitz.com/edit/react-ts-z5d6tr?file=Hello.tsx
We can disable the button by passing a boolean value to the disabled attribute. In the above example, we are using the react hooks useState hook to initialize the state.
disabled: when actions are not available. loading: add loading spinner in button, avoiding multiple submits too. There are primary button, default button, dashed button, text button and link button in antd.
If you wrap your submit button in a Form.Item like this, it should disable it until all required fields are completed. The rest of the form would remain the same. Show activity on this post.
A button means an operation (or a series of operations). Clicking a button will trigger corresponding business logic. In Ant Design we provide 5 types of button. Primary button: indicate the main action, one primary button at most in one section. Default button: indicate a series of actions without priority.
I found some elegant way to perform this
<Form.Item shouldUpdate className="submit">
{() => (
<Button
type="primary"
htmlType="submit"
disabled={
!form.isFieldsTouched(true) ||
form.getFieldsError().filter(({ errors }) => errors.length)
.length > 0
}
>
Log in
</Button>
)}
</Form.Item>
I'm going to paste here my solution in case anyone finds it useful.
Note; this solution uses the hook Form.useForm()
and the callback onFieldsChange
.
The validation is not included in this excerpt. But the idea is that when the form changes (any field) it will set the submit button (in this case inside the Modal) to disabled/enabled.
const LoginForm = () => {
const [form] = useForm();
const [disabledSave, setDisabledSave] = useState(true);
const handleFormChange = () => {
const hasErrors = form.getFieldsError().some(({ errors }) => errors.length);
setDisabledSave(hasErrors);
}
return (
<Modal okButtonProps={{ disabled: disabledSave }} onOk={form.submit}>
<Form onFieldsChange={handleFormChange} form={form}>
<Item name="username" label="username">
<Input />
</Item>
<Item name="password" label="password">
<Input />
</Item>
</Form>
</Modal>
)
};
I found a nice solution here that doesn't involve any additional state. If you wrap your submit button in a Form.Item
like this, it should disable it until all required fields are completed. The rest of the form would remain the same.
<Form.Item
noStyle
shouldUpdate
>
{({ getFieldsValue }) => {
const { username, password } = getFieldsValue();
const formIsComplete = !!username && !!password;
return (
<Button
type="primary"
htmlType="submit"
disabled={!formIsComplete}
>
Log In
</Button>
);
}}
</Form.Item>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With