When using the Form component in Ant Design (AntD), getFieldError is a function used to retrieve error messages for form fields, which is part of the API provided by Form.Item. This function is highly useful, particularly during form validation, as it effectively presents specific error messages to users.
Basic Usage
When using AntD's form, you should ensure that the form component is wrapped with the Form.create() higher-order component. This automatically injects getFieldDecorator and getFieldError among other APIs into the form's props.
The basic usage of getFieldError is as follows:
javascriptgetFieldError(fieldId)
Here, fieldId is the field ID specified in getFieldDecorator.
Example
Consider a simple login form with two fields: username and password. We want to validate these fields and display the corresponding error messages when the form is submitted.
javascriptimport React from 'react'; import { Form, Input, Button } from 'antd'; class LoginForm extends React.Component { handleSubmit = e => { e.preventDefault(); this.props.form.validateFields((err, values) => { if (!err) { console.log('Received values of form: ', values); } }); }; render() { const { getFieldDecorator, getFieldError } = this.props.form; // Retrieve field error messages const usernameError = getFieldError('username'); const passwordError = getFieldError('password'); return ( <Form onSubmit={this.handleSubmit}> <Form.Item validateStatus={usernameError ? 'error' : ''} help={usernameError || ''} > {getFieldDecorator('username', { rules: [{ required: true, message: 'Please enter a username!' }], })( <Input placeholder="Username" /> )} </Form.Item> <Form.Item validateStatus={passwordError ? 'error' : ''} help={passwordError || ''} > {getFieldDecorator('password', { rules: [{ required: true, message: 'Please enter a password!' }], })( <Input type="password" placeholder="Password" /> )} </Form.Item> <Button type="primary" htmlType="submit">Login</Button> </Form> ); } } const WrappedLoginForm = Form.create()(LoginForm); export default WrappedLoginForm;
Explanation
In the above code:
getFieldDecoratoris used to register form items and bind related validation rules.- In each
Form.Item, we use thevalidateStatusandhelpproperties to display the validation status and error messages for the field. The values of these properties are obtained throughgetFieldErrorto retrieve specific error messages. - When the form is submitted and
validateFieldsis called, the form data is processed only if all rules are satisfied; otherwise, the corresponding error messages are displayed on the interface usinggetFieldError.
By using this approach, getFieldError provides a very intuitive and user-friendly way to display form field validation errors. This is crucial for enhancing user experience and form interactivity.