Formik验证正在提交/isValiating未设置为True

2022-09-25 00:00:00 reactjs forms javascript formik

我有一个我的用户请求的表单,我清楚地表明该表单是无效的。因此,我计划弹出一个sweetalert对话框,让他们知道他们需要再次检查表单。我想我可以在验证中这样做,以便在提交尝试失败时向他们发出警报:

const validate = values => {
    console.log(formik.isSubmitting); // always prints false
    console.log(formik.isValidating); // always prints false
    const errors = {};
    if (!values.name) {
      errors.name = 'Required';
    }

    if (Object.keys(errors).length > 0 && formik.isSubmitting) {
        Swal.fire({
            icon: 'error',
            title: "Oops. . .",
            text: "There are errors with the form. Please double check your options.",
            footer: "<div>Problems: " + Object.keys(errors).join(', ') + "</div>"
        })
    }

    return errors;
};

const formik = useFormik({
    initialValues: {
        name: item.name
    },
    enableReinitialize: true,
    validate,
    onSubmit: values => {
       // also tried adding 
       formik.setSubmitting(true); 
       //do stuff
    }
})

isSubmitting / isValidating始终为假。我是否需要向validate函数传递其他道具才能访问这些值?

https://codesandbox.io/s/nervous-wescoff-cf2y1?file=/src/App.js


解决方案

我认为validate方法不适合向用户显示对话框。 您的用例看起来像是Formik库中的一个定制需求。分享他们在内部提交表单时所做的工作-https://formik.org/docs/guides/form-submission。

您可以添加用于提交的自定义方法。

因此, 我已将您的沙盒分叉并进行了更新-https://codesandbox.io/s/custom-form-submit-stackoverflow-8znzf

让我知道你的想法。

编辑:添加代码,以便即使链接过期,您仍可以知道如何操作

import React, { useState } from "react";
import "./styles.css";
import { useFormik } from "formik";
import Swal from "sweetalert2";
import "bootstrap/dist/css/bootstrap.min.css";

export default function App() {
  const [item, setItem] = useState({
    name: "",
    email: ""
  });

  const validate = (values) => {
    console.log("values: ", values);
    const errors = {};
    if (!values.name) {
      errors.name = "Required";
    }
    return errors;
  };

  const initialValues = {
    name: item.name,
    email: item.email
  };

  const formik = useFormik({
    initialValues,
    enableReinitialize: true,
    validate,
    onSubmit: (values) => {
      console.log("inside onSubmit", values);
    }
  });

  const customSubmitHandler = (event) => {
    event.preventDefault();
    const touched = Object.keys(initialValues).reduce((result, item) => {
      result[item] = true;
      return result;
    }, {});
    // Touch all fields without running validations
    formik.setTouched(touched, false);
    formik.setSubmitting(true);

    formik
      .validateForm()
      .then((formErrors) => {
        if (Object.keys(formErrors).length > 0) {
          Swal.fire({
            icon: "success",
            title: "Yes. . .",
            text: "This one should fire if everything is working right",
            footer:
              "<div>Problems: " + Object.keys(formErrors).join(", ") + "</div>"
          });
        } else {
          formik.handleSubmit(event);
        }
        formik.setSubmitting(false);
      })
      .catch((err) => {
        formik.setSubmitting(false);
      });
  };

  return (
    <form id="campaignForm" onSubmit={customSubmitHandler}>
      <div className="form-group">
        <label htmlFor="name">Name</label>
        <input
          id="name"
          type="text"
          onChange={formik.handleChange}
          value={formik.values.name}
          className="form-control"
          placeholder="Enter name"
        />
        {formik.errors.name ? (
          <div className="text-danger">{formik.errors.name}</div>
        ) : null}
      </div>
      <div className="form-group">
        <label htmlFor="name">Email</label>
        <input
          id="name"
          type="email"
          onChange={formik.handleChange}
          value={formik.values.email}
          className="form-control"
          placeholder="Enter email"
        />
        {formik.errors.email ? (
          <div className="text-danger">{formik.errors.email}</div>
        ) : null}
      </div>
      <div className="form-group">
        <button className="btn btn-info" type="submit">
          Submit
        </button>
      </div>
    </form>
  );
}

相关文章