Home > other >  Ant design form not validating
Ant design form not validating

Time:09-17

So I was trying to follow the docs, and came up with this:

Here's a simple example:

import { Button, Form, Input } from "antd";

export default function App() {
  const [form] = Form.useForm();
  return (
    <Form form={form} onFinish={(data) => console.log(data)}>
      <Form.Item
        rules={[{ required: true, message: "test message" }]}
        label="test"
      >
        <Input />
      </Form.Item>
      <Button htmlType="submit">Submit</Button>
    </Form>
  );
}

along with a enter image description here

But no such thing happens. onFinish says that form data is an empty object, and the validation doesn't run. So I must be missing smth. Any idea what?

CodePudding user response:

You need to set the name prop for Form.Item component.

import "./styles.css";
import { Button, Form, Input } from "antd";

export default function App() {
  const [form] = Form.useForm();
  return (
    <Form form={form} onFinish={(data) => console.log(data)}>
      <Form.Item
        rules={[{ required: true, message: "test message" }]}
        name="username"
        label="test"
      >
        <Input />
      </Form.Item>
      <Button htmlType="submit">Submit</Button>
    </Form>
  );
}

Log:

async-validator: 
(1) ["'username' is required"]
  • Related