Display an error if the password and login are incorrect in Form. Antd React

Viewed 662

The task is as follows, when you press the LOGIN button, a request is sent to the server with a password and login, if they are incorrect, then under the password entry line you need to display the corresponding error and all input fields should be highlighted in red. How can you achieve this?

I tried to do it for a very long time using built-in validators in Form.Item . So, since I don't need to worry about changing the color of input fields, the validator does it itself, but I got confused about these validators and I got an infinite loop.

Here is some of the code for the Login page.

export const LoginPage = () => {
  const { dispatch } = useAuthContext()

  const onFinish = (values: any) => {
    APIs.requestLogin(values.username, values.password, false)
      .then((response: any) => {
        dispatch({ type: SIGN_IN, payload: response.data })
      })
      .catch(() => {
        console.log('error')
      })
  }

  return (
    <div className={classes.root}>
      <div className={classes.container}>
        <Form
          className={classes.form_container}
          name="normal_login"
          initialValues={{ remember: true }}
          onFinish={onFinish}
        >
          <Form.Item
            className={classes.form_input}
            name="username"
            rules={[{ required: true, message: 'Please enter your username!' }]}
          >
            <Input
              autoFocus={true}
              className={classes.input_style}
              placeholder="Username"
              prefix={<UserOutlined className="site-form-item-icon" />}
            />
          </Form.Item>

          <Form.Item
            className={classes.form_input}
            name="password"
            rules={[{ required: true, message: 'Please enter your password!' }]}
          >
            <Input.Password className={classes.input_style} placeholder="Password" prefix={<LockOutlined />} />
          </Form.Item>

          <Form.Item className={classes.form_submit}>
            <Button className={classes.form_button_submit} type="primary" htmlType="submit">
              LOGIN
            </Button>
          </Form.Item>
        </Form>
        <div className={classes.image} />
      </div>
    </div>
  )
}
0 Answers
Related