Formik ReactBoostrap表单未验证

时间:2020-10-11 19:17:44

标签: reactjs react-bootstrap formik yup react-bootstrap-form

我在react-boostrap表单上构建了formik表单。我有一个自定义onchange来处理输入。问题是即使表单字段中有一个值,也会引发验证错误。同样,如果键入一些值,则错误消息不会消失。我想验证根本不起作用。请帮助我。

这是react-bootstrap格式https://react-bootstrap.github.io/components/forms/#forms-validation-libraries

的代码
import React from "react";
import * as yup from "yup";

export default function StepByStepForm() {
  const [myForm, setMyForm] = useState({});

  const handleInput = (e) => {
    const value = e.target.value;
    const name = e.target.name;
    setMyForm((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  const form1schema = yup.object({
    company_name: yup.string().required(),
  });

  function Step1Form() {
    return (
      <Formik validationSchema={form1schema}>
        {({
          touched,
          isValid,
          isInvalid,
          errors,
          handleBlur,
          handleChange,
          values,
          validateForm,
        }) => (
          <Form noValidate className="formstep1">
            <Form.Group controlId="addCompany">
              <Form.Label>Company Name*</Form.Label>
              <Form.Control
                name="company_name"
                type="text"
                value={myForm.company_name}
                onChange={handleInput} // have my custom handling
                isInvalid={!!errors.company_name}
              />
              <Form.Control.Feedback type="invalid">
                {errors.company_name}
              </Form.Control.Feedback>
            </Form.Group>

            <div className="step-progress-btn">
              <Button variant="primary" onClick={() => validateForm()}>
                Validate
              </Button>
            </div>
          </Form>
        )}
      </Formik>
    );
  }

  return <div>Step1Form()</div>;
}

2 个答案:

答案 0 :(得分:0)

您的自定义onChange={handleInput}函数永远不会将值传递给Formik。

Formik在内部跟踪您的表单值,因此您不需要像现在(useState)那样使用const [myForm, setMyForm] = useState({});方法添加它。

向表单添加自定义onChange时,您会更改组件状态,而Formik的状态永远不会更新,因此Yup没有要验证的值。

如果将其添加到结束</Form>标签下面,您将看到Formik从不读取表单的更新值:

<pre>
  {JSON.stringify(
    {
      touched,
      isValid,
      isInvalid,
      errors,
      handleBlur,
      handleChange,
      values,
      validateForm
    },
    null,
    2
  )}
</pre>

答案 1 :(得分:0)

问题在于Formik-Yup需要onChange = {handleChange}进行验证

如果在handleChange之上具有自定义或其他功能,则需要在handlechange之上添加事件监听器

import React from "react";
import * as yup from "yup";

export default function StepByStepForm() {
  const [myForm, setMyForm] = useState({});

  const handleInput = (e) => {
    const value = e.target.value;
    const name = e.target.name;
    setMyForm((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  const form1schema = yup.object({
    company_name: yup.string().required(),
  });

  function Step1Form() {
    return (
      <Formik validationSchema={form1schema}>
        {({
          touched,
          isValid,
          isInvalid,
          errors,
          handleBlur,
          handleChange,
          values,
          validateForm,
        }) => (
          <Form noValidate className="formstep1">
            <Form.Group controlId="addCompany">
              <Form.Label>Company Name*</Form.Label>
              <Form.Control
                name="company_name"
                type="text"
                value={myForm.company_name}
                onChange={(e) => {
                  handleChange(e);
                  handleInput(e);
                }}
                isInvalid={!!errors.company_name}
              />
              <Form.Control.Feedback type="invalid">
                {errors.company_name}
              </Form.Control.Feedback>
            </Form.Group>

            <div className="step-progress-btn">
              <Button variant="primary" onClick={() => validateForm()}>
                Validate
              </Button>
            </div>
          </Form>
        )}
      </Formik>
    );
  }

  return <div>Step1Form()</div>;
}