Form validation at server side. How to show validation message in form? (React / Formik / Antd)

Viewed 433

For example form with only email field:

const RegistrationForm = (props) => {
  const { values, touched, errors, handleChange, handleBlur, handleSubmit, status } = props;

  const emailFieldHelp = () => {
     const { touched, errors, status, setStatus } = props;
     console.log('status: ', status);
     if (touched.email && errors.email) {
       return errors.email;
     }

     if (status && !status.isUserAdded) {
       setStatus({"isUserAdded": false});
       return "User already exist";
     }
     return null;
   };

  return (
    <Form onFinish={handleSubmit}>
    <Form.Item
          help={emailFieldHelp()}
          validateStatus={setFieldValidateStatus('email')}
          label="E-mail"
          name="email"
          hasFeedback={touched.email && values.email !== ''}
        >
         <Input
           placeholder="Email"
           value={values.email}
           onChange={handleChange}
           onBlur={handleBlur}
         />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">Submit</Button>
        </Form.Item>
        </Form>
  )
};
const RegFormView = withFormik({
  validationSchema,
  mapPropsToValues: () => ({
    email: ''
  }),

  handleSubmit: async (values, { setErrors, setSubmitting, setStatus }) => {
    await userService.createUser('/signup/', values)
        .then(response => {
          setStatus('');
          const status = (response.isAdded)
              ? {isUserAdded: true}
              : {isUserAdded: false};
          setStatus(status);
          setSubmitting(false);
          }, (error) => {
            setErrors(error);
         });
     },
})(RegistrationForm);

When I send form and validate it on sever side, I return 'isAdded' = false or true. Than I set status to {isUserAdded: true} or false if user not added. and I absolutely have no idea how to show this message in form under email field and keep form working. Now I can show message but than I cant send form second time becouse of status already set to {isUserAdded: true}. Do I need somehow to change status when user change email field? but I can't do it becouse of the formik.

here onChange={handleChange} I can pass only handleChange and can't run my function or I can run my function like this onChange={myFunc()} but than its seems impossible to pass handleChange to Formik. (I dont need call it like this handleChange(e) its not work! i need somehow pass it to Formik) I'm total stuck. If you have knowledge in react plz help.

And if you know some examples how to show server side validation messages in react form, links to this examples might be helpful. ty.

0 Answers
Related