React ant design form validation not working (on submit)

Issue

When i press submit and if there is nothing filled in email/password a message should appear beneath them saying email/password is required but its not happnening

Code Sandbox Link: https://codesandbox.io/s/gracious-hypatia-ieepw?file=/src/App.js:0-1221

import './App.css';
import {Button, Form, Input, Checkbox} from 'antd'
import 'antd/dist/antd.css';

function App() {
  return (
    <div className="App">
      
  <Form
      name="basic"
      initialValues={{
        remember: true,
      }}
    >
      <h1 className="Title">Sign Up</h1>
      <h2 className="Text">Enter Email :</h2>
      <Form.Item
        rules={[
          {
            required: true,
            message: 'Please input your email!',
          },
        ]}
      >
        <Input placeholder="Enter Email" />
      </Form.Item>
      <h2 className="Text">Enter Password :</h2>
      <Form.Item
        rules={[
          {
            required: true,
            message: 'Please input your password!',
          },
        ]}
      >
        <Input.Password placeholder="Enter Password" />
      </Form.Item>

      <Form.Item  name="remember" valuePropName="checked">
        <Checkbox>Remember me</Checkbox>
      </Form.Item>

      <Form.Item >
        <div className="Button">
        <Button type="primary" htmlType="submit" size="medium">
          Submit
        </Button>
        </div>
      </Form.Item>
    </Form>
    </div>
  );
}

export default App;```

Solution

You need to specify name property for your Form.Item components. The antd form utilities work with name. So, because you haven’t defined name for your text input fields, it can not validate or read its value.
You should change your Form.Item like this:

      <Form.Item
        name="email"
        rules={[
          {
            required: true,
            message: 'Please input your email!',
          },
        ]}
      >
        <Input placeholder="Enter Email" />
      </Form.Item>

      <Form.Item
        name="password"
        rules={[
          {
            required: true,
            message: 'Please input your password!',
          },
        ]}
      >
        <Input.Password placeholder="Enter Password" />
      </Form.Item>

Answered By – Hossein Ahmadi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published