是的模式 - `when` 方法不起作用

Yup schema - `when` method is not working

最近我正在为创建 yup 模式而苦恼。因为我这样做了,所以我发现 when() 方法完全不适合我,就像文档所说的那样,以及我在互联网上找到的其他解决方案。 当我的复选框被选中 true 时,架构上的所有字段都应该是 required,但它们不是。如我的示例所示,我尝试了三种方法,其中 none 有效。也许有人知道我做错了什么?

我的测试代码是:

import "./styles.css";
import * as yup from "yup";
import { FormProvider, useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import React, { useEffect } from "react";

export default function App() {
  const schema = yup.object({
    isRequired: yup.bool(),
    firstName: yup.string().when("isRequired", (_, schema) => {
      return schema.required();
    }),
    lastName: yup.string().when("isRequired", () => {
      return yup.string().required();
    }),
    contact: yup.string().when("isRequired", {
      is: true,
      then: yup.string().required("Required")
    })
  });

  const methods = useForm({
    mode: "all",
    defaultValues: {
      isRequired: true,
      firstName: "",
      lastName: "",
      contact: ""
    },
    resolver: yupResolver(schema),
    shouldUnregister: true
  });

  const { register, watch } = methods;
  const isRequired = watch("isRequired");

  useEffect(() => {
    console.log(schema.fields);
  }, [isRequired, schema]);

  return (
    <FormProvider {...methods}>
      <form autoComplete="off" noValidate>
        <input type="checkbox" {...register("isRequired")} />
        <input {...register("firstName")} />
        <input {...register("lastName")} />
        <input {...register("contact")} />
      </form>
    </FormProvider>
  );
}

https://codesandbox.io/s/infallible-wildflower-dsyon

您关于如何使用 when 的第三个解决方案是正确的。它不起作用的原因是,在 firstNamelastName 的前两个 when 语句中,您总是 return yups required 方法而不检查是否 isRequiredtrue.

const schema = yup.object({
  isRequired: yup.bool(),
  firstName: yup.string().when("isRequired", {
    is: true,
    then: yup.string().required()
  }),
  lastName: yup.string().when("isRequired", {
    is: true,
    then: yup.string().required()
  }),
  contact: yup.string().when("isRequired", {
    is: true,
    then: yup.string().required("Required")
  })
});

这是将函数传递给 when 时的处理方式。

const schema = yup.object({
  isRequired: yup.bool(),
  firstName: yup
    .string()
    .when("isRequired", (isRequired, schema) =>
      isRequired ? yup.string().required() : schema
    ),
  lastName: yup
    .string()
    .when("isRequired", (isRequired, schema) =>
      isRequired ? yup.string().required() : schema
    ),
  contact: yup
    .string()
    .when("isRequired", (isRequired, schema) =>
      isRequired ? yup.string().required() : schema
    )
});