How to get error message by getFieldError in AntD Form?

Solution 1:

Your console.log will invoke, every time your component renders, so you need to rerender your component whenever validation applies on the form. To handle this situation you can use render prop with Form component, like this:

function CustomFormItem({ error, ...other }) {
  console.log(error)
  return <Input.Password placeholder="Enter your password" {...other} />;
}

function MyForm() {
  const [form] = Form.useForm();
  const onFinish = (values) => {
    console.log(values);
  };

  return (
      <Form
        form={form}
        name="login_form"
        onFinish={onFinish}
        scrollToFirstError
      >
        {(values,formInstance) => {
          return (
            <>
              <Form.Item
                label="Password"
                name="password"
                rules={[
                  {
                    required: true,
                    message: 'Password cannot be empty!',
                  },
                ]}
                help="" // hide validating message.
              >
                <CustomFormItem error={formInstance.getFieldError('password')} />
              </Form.Item>
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  Submit
                </Button>
              </Form.Item>
            </>
          );
        }}
      </Form>
  );
}

Consider that with above implementation, render prop will call with every change on the form.

Solution 2:

Use can use getFieldError(); like the code example below

Function as Child Component is not working perfectly inside <Form.Item> component as of now.

 <Form {...layout} form={form} name="control-hooks" onFinish={onFinish}>
      {(values, formInstance) => {
        console.log(formInstance.getFieldError("password")[0]);
        return (
          <>
            <Form.Item
              name="password"
              label="Password"
              rules={[
                {
                  required: true
                }
              ]}
            >
              <Input />
            </Form.Item>
          </>
        );
      }}
    </Form>