如果某个逻辑没有通过,我可以在提交时在 Antd 输入字段下应用自定义错误消息吗?

Can I apply a custom error message under an Antd input field on submit if a certain logic does not pass?

如果不满足某些条件,我正在尝试在表单提交的 Antd 输入下呈现错误消息。在我的具体情况下,如果 !this.isNew && this.state.hasTypedLocation && !this.state.hasChosenLocation,我想呈现一条错误消息。现在我只是在控制台中记录一个错误。 Antd 是否提供某种类似的功能?

我有以下输入:

    <Form.Item
      name="searchBox"
      rules={[
        {
          required: true,
          message: <IntlMessages id="common.error_address" />,
        },
      ]}
    >
      <Input
        type="text"
        placeholder={intl.formatMessage({ id: 'common.error_address' })}
        onChange={onChangeHandlerAddress}
        value={facilityData.address1}
      />
    </Form.Item>

我有以下功能可以保存我的实体:

  saveFacility(event) {
    event.persist();
    event.preventDefault();

    this.formRef.current
      .validateFields(['name', 'organization', 'customer', 'searchBox'])
      .then((values) => {
        const { actions } = this.props;
        const { facility } = this.state;
        if (!this.isNew && this.state.hasTypedLocation && !this.state.hasChosenLocation ) {
          console.log('error')
        } else {
          actions.saveFacility(facility);
        }
      })
      .catch((error) => {
        console.log(error);
      });
  }

您可以将触发自定义错误消息的验证器函数作为规则传递给 Form.Item。验证器应该 return 一个 Promise。示例:

<Form.Item
  name="searchBox"
  rules={[
    {
      required: true,
      message: <IntlMessages id="common.error_address" />,
    },{
      // Validator function example
      validator: (rule, value) => {
      if (!this.isNew && this.state.hasTypedLocation && !this.state.hasChosenLocation ) {
        return Promise.reject("Custom Error Message!!");
      } else {
        return Promise.resolve();
      }
    },
  ]}
>
  <Input
    type="text"
    placeholder={intl.formatMessage({ id: 'common.error_address' })}
    onChange={onChangeHandlerAddress}
    value={facilityData.address1}
  />
</Form.Item>