I have a simple Form
that checks for user's input values such as name, email and address and validates them. So far I have successfully achive this. But I have a submit button
as the last Form.Item
which I want to only enable when all input fields are filled and validated.
How should I check for this and subsequently set the state formCompleted
which toggles the disabling of button?
Check this example https://ant.design/components/form/#components-form-demo-horizontal-login.
function hasErrors(fieldsError) {
return Object.keys(fieldsError).some(field => fieldsError[field]);
}
class HorizontalLoginForm extends React.Component {
componentDidMount() {
// To disabled submit button at the beginning.
this.props.form.validateFields();
}
handleSubmit = e => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
console.log('Received values of form: ', values);
}
});
};
render() {
const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched } = this.props.form;
// Only show error after a field is touched.
const usernameError = isFieldTouched('username') && getFieldError('username');
return (
<Form layout="inline" onSubmit={this.handleSubmit}>
<Form.Item validateStatus={usernameError ? 'error' : ''} help={usernameError || ''}>
{getFieldDecorator('username', {
rules: [{ required: true, message: 'Please input your username!' }],
})(
<Input placeholder="Username" />,
)}
</Form.Item>
<Form.Item>
<Button htmlType="submit" disabled={hasErrors(getFieldsError())}>
Log in
</Button>
</Form.Item>
</Form>
);
}
}
The example checks if getFieldsError
has any values to determine if the button should be disabled or not. When the form first mounts, it uses validateFields
to validate your inputs and updates getFieldsError
. The problem with this is that errors will show before any inputs happen which is why it then checks if the fields have been touched before before it shows the errors using isFieldTouched
.
Hope that helps!