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

Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)

本文介绍了Formik验证正在提交/isValiating未设置为True的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我的用户请求的表单,我清楚地表明该表单是无效的。因此,我计划弹出一个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>
  );
}

这篇关于Formik验证正在提交/isValiating未设置为True的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Formik验证正在提交/isValiating未设置为True