Recently, the antD UI has been used to submit data from forms, including arrays and objects. It’s a pain to have to validate parameters when you submit. After reviewing the documentation, I found that ANTD’s Form component did a great job, and none of these requirements were a problem. Now to sum up.

  • As the figure shows, the submitted form information has more than one thing to fill in. The data type is Array.

How does an array format render with a Form component?

Form.List

  • Now let’s customize a form property as an array of form data.
import { useState } from "react";
import { Button, Col, Form, Input, Row } from "antd";
import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons";

function validator(_, val) {
  if(! val) {return Promise.reject(new Error("Added price is mandatory!"));
  }
  if (!/^\d+$/.test(val) || val <= 0) {
    return Promise.reject(new Error("The price must be numerical and greater than zero."));
  }
  return Promise.resolve();
}
function validators(_, vals) {
  console.log(vals);
  if(! vals || vals.length ===0) {
    return Promise.reject("Please fill in the price!");
  }
  return Promise.resolve();
}
export default function MyForm() {
  const [formInstance] = Form.useForm();
  const submit = () = > {
    // Click verify form information
    formInstance.validateFields().then((vals) = > {
      console.log(vals);
    });
  };
  return (
    <Form form={formInstance} labelCol={{ span: 2 }} wrapperCol={{ span: 6}} >
      <Form.List name="price" rules={[{ validator: validators}}] >
        {(fields, { add, remove }, { errors }) => (
          <div>
            {fields.map((field) => {
              return (
                <Form.Item
                  {. field}
                  key={field.name}
                  rules={[{ validator: validator}}]validateTrigger={["onChange","onBlur"]}
                >
                  <Input
                    suffix={
                      <MinusCircleOutlined onClick={()= > remove(field.name)} />
                    }
                  />
                </Form.Item>
              );
            })}
            <Row style={{ marginBottom: 20}} >
              <Button
                type="dashed"{/* Click Add column */}onClick={()= > {
                  add();
                }}
                icon={<PlusOutlined />} > Add price</Button>
            </Row>{/* formList validation error */}<Form.ErrorList errors={errors} />
          </div>
        )}
      </Form.List>
      <Row>
        <Button type="primary" onClick={submit}>
          submit
        </Button>
      </Row>
    </Form>
  );
}
Copy the code
  • This is verified when you click submit formForm.ListAnd the child nodeForm.Item. If there is one on the noderules, the submitted data is in array format. As shown in figure

Custom Form components, used under the form. Item component.

The props of the form. Item child accepts two arguments: value,onChange.

props type describe
value any Corresponding to the formForm.ItemonnameThe value of the.
onChange function Modify form property values.
// Since the value defined contains fisrt and last attributes, the Object type is used. Default empty object
function Name({ value = {}, onChange }) {
  const [first, setFirst] = useState(null);
  const [last, setLast] = useState(null);
  // Call onChange when the value changes because we are using an object.
  const triggerChange = (checkVal) = > {
    onChange &&
      onChange({
        first: first,
        last: last, ... value, ... checkVal, }); };const firstChange = (e) = > {
    const val = e.target.value;
    setFirst(val);
    triggerChange({ first: val });
  };
  const lastChange = (e) = > {
    const val = e.target.value;
    setLast(val);
    triggerChange({ last: val });
  };
  return (
    <Row justify="center">
      <Col span={12}>
        <Input
          placeholder="first name"
          value={value.first || first}
          onChange={firstChange}
        />
      </Col>
      <Col span={12}>
        <Input
          placeholder="last name"
          value={value.last || last}
          onChange={lastChange}
        />
      </Col>
    </Row>
  );
}
Copy the code
// Append a little content to the MyForm component above
function MyForm() {
  / /... This remains the same
  return (
    <Form form={formInstance} labelCol={{ span: 2 }} wrapperCol={{ span: 6}} >{/ *... . Ignore form. List*/}<Form.Item name="username" label="username">
        <Name />
      </Form.Item>
      <Row>
        <Button type="primary" onClick={submit}>
          submit
        </Button>
      </Row>
    </Form>
  );
}
Copy the code
  • If you need to use forms to validate the values of a custom component, use theForm.ItemTo addrules, the use ofvalidatorFunction to customize validation rules.