我想在 Yup 中转换值,但 formik 没有返回正确的值

I want to transform value in Yup but formik is not returning the correct value

我想将电子邮件中的值转换为小写。它正在将 Yup 中的值转换为小写。但是 formik 正在返回错误值。所以我只想以这种方式制作它,就像当我输入大写的电子邮件时它应该自动将其转换为小写。

这是我的可重现代码。

import React from "react";
import { render } from "react-dom";
import { Formik } from "formik";
import * as Yup from "yup";

import { DisplayFormikState } from "./helper";
import "./style.css";

const validationSchema = Yup.object({
  email: Yup.string()
    .transform(function (value, originalvalue) {
      return this.isType(value) && value !== null ? value.toLowerCase() : value;
    })
    .email()
    .required()
    .label("Email")
});

const App = () => (
  <div className="app">
    <Formik
      initialValues={{ name: "" }}
      onSubmit={() => {}}
      validationSchema={validationSchema}
    >
      {(props) => {
        const { handleBlur, handleChange, values, errors, touched } = props;
        return (
          <form onSubmit={props.handleSubmit}>
            <h1>Email Form</h1>

            <input
              type="email"
              name="email"
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.email}
            />
            {errors.email && touched.email && errors.email}

            <button type="submit">Submit</button>

            <DisplayFormikState {...props} />
          </form>
        );
      }}
    </Formik>
  </div>
);

render(<App />, document.getElementById("root"));

在您的表单中,Formik 和 Yup 基本上有两个独立的职责:

  • Formik 管理表单的状态(值)
  • Yup 执行验证并告诉 Formik 这些值是否有效

是的,不会设置您表单中的值。

从 Yup 转换中删除大小写转换。相反,只需将值设置为小写并在 yup 进行验证之前将其传递给 setFieldValue()


const validationSchema = Yup.object({
  email: Yup.string()
    .transform(function (value, originalvalue) {
      return this.isType(value);
    })
    .email()
    .required()
    .label("Email")
});

const App = () => (
  <div className="app">
    <Formik
      initialValues={{ name: "" }}
      onSubmit={() => {}}
      validationSchema={validationSchema}
    >
      {(props) => {
        const { handleBlur, setFieldValue, values, errors, touched } = props;
        return (
          <form onSubmit={props.handleSubmit}>
            <h1>Email Form</h1>

            <input
              type="email"
              name="email"
              onChange={(e)=>{
                const value = e.target.value || "";
                setFieldValue('email', value.toLowerCase());
              }}
              onBlur={handleBlur}
              value={values.email}
            />
            {errors.email && touched.email && errors.email}

            <button type="submit">Submit</button>

            <DisplayFormikState {...props} />
          </form>
        );
      }}
    </Formik>
  </div>
);

render(<App />, document.getElementById("root"));