乐闻世界logo
搜索文章和话题

How to get error message by getFieldError in AntD Form?

1个答案

1

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:

javascript
getFieldError(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.

javascript
import 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:

  1. getFieldDecorator is used to register form items and bind related validation rules.
  2. In each Form.Item, we use the validateStatus and help properties to display the validation status and error messages for the field. The values of these properties are obtained through getFieldError to retrieve specific error messages.
  3. When the form is submitted and validateFields is called, the form data is processed only if all rules are satisfied; otherwise, the corresponding error messages are displayed on the interface using getFieldError.

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.

2024年8月9日 20:43 回复

你的答案