Skip to content
Advertisement

How can I use AntD FormInstance functions correctly?

I’m trying to validate user’s input before they submit the form. How can I pass input field values to my validateInput function and if it returns false trigger and apply the following properties in the field hasFeedback, validateStatus and help

const Demo = () => {
  const [form] = form.useForm();
  const onFinish = (values) => {
    console.log("Success:", values);
  };

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  const validateInput = (input) => {
    const isEmailFormatValid = `regex...`;
    var check = input.match(validateFormat);
    return check
  };

  return (
    <Form
      form={form}
      name="basic"
      initialValues={{
        remember: true,
      }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
    >
      <Form.Item
        label="Email"
        name="email"
        / * hasFeedback 
        validateStatus="warning"
        help="Invalid email format" */
        rules={[
          {
            required: true,
            message: "Please input your email!",
          },
        ]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="Password"
        name="password"
        rules={[
          {
            required: true,
            message: "Please input your password!",
          },
        ]}
      >
        <Input.Password />
      </Form.Item>
      <Form.Item>
        <Button block type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
  );
};

Advertisement

Answer

<Form.Item> prop rules is an array so you can add many rules to it.

If you want to check if the email input is not empty at the same time a valid email, you can do this:

<Form.Item
  label="Email"
  name="email"
  rules={[
    {
      required: true,
      message: "Please input your email!",
    },
    {
      pattern: /your email regex here/,
      message: "Invalid email format",
    },
  ]}
>
  <Input />
</Form.Item>

No need for extra validation function. The error will automatically show if not meet the specified regex.

You can see all the rules of ant design input here

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement