Search code examples
reactjsformsvalidationantd

How to add general validation error message in form?


I have a form (antd) divided to a few sections, and in each section there are a lot of Form.Items, and each Form.Item has rules like required, specific type, etc.

in case there are any errors in the validation of any Field.Item - I want there to be a single specific, hard-coded string error message at the title of the relevant section, instead of the error-message that the Form.Item rule validation adds under each Form.Item.

is there support for a custom specific validation-error message I can use?

I thought about using some custom rules and just use a useState as a flag for the custom-error-message, but I want to know if there is a build-in option too

this is a really general question about the usage of 'Form' from antd, but I'm adding a general code for reference -

<Form>
   <Form.Item
    name={["firstSection","name"]}
    rules={[{ required: isRequired, message: "" }]}
    >
      <Input>
    </Form.Item>

   <Form.Item
    name={["firstSection","phoneNumber"]}
    rules={[{ required: isRequired, message: "" }]}
    >
      <Input>
    </Form.Item>

   <Form.Item
    name={["firstSection","fax"]}
    rules={[{ required: isRequired, message: "" }]}
    >
      <Input>
    </Form.Item>


   <Form.Item
    name={["secondSection","city"]}
    rules={[{ required: isRequired, message: "" }]}
    >
      <Input>
    </Form.Item>

   <Form.Item
    name={["firstSection","address" ]}
    rules={[{ required: isRequired, message: "" }]}
    >
      <Input>
    </Form.Item>

   <Form.Item
    name={["firstSection","country"]}
    rules={[{ required: isRequired, message: "" }]}
    >
      <Input>
    </Form.Item>
</Form

Solution

  • following the open issue that @DevThiman showed me (https://github.com/ant-design/ant-design/issues/15674)

    I ended up using this for a solution -

        const checkSectionErrors = async (fieldNames) => {
        const form = Form.useFormInstance();
        await form.validateFields();
        const errors = form.getFieldsError(fieldNames);
        const existingErrors = errors.find(({ errors }) => errors.length);
        return !!existingErrors;
      };
    
      const isFirstSectionInvalid = checkSectionErrors([
        ["secondSection", "city"],
        ["secondSection", "address"],
        ["secondSection", "country"]
      ]);
      const isSecondSectionInvalid = checkSectionErrors([
        ["firstSection", "phoneNumber"],
        ["firstSection", "name"],
        ["firstSection", "fax"]
      ]);