Reactjs 和 Yup,react-hook-form 集成的问题

Reactjs and Yup, problem with react-hook-form integration

我正在使用 yup 和 react-hook-forms 来验证用户提交。我正在创建一个发送短信、电子邮件和推送通知的应用程序。用户可以通过一组复选框指定他们希望联系的地点。这 3 个复选框更新一个默认情况下如下所示的有状态对象:

  const [checkboxes, setCheckboxes] = useState({
    phone: false,
    email: false,
    push: false,
  });

在提交表单之前,我需要验证至少其中一个已更改为 true,如果没有,我想抛出一条错误消息.为此,我找到了 yup 的 .test 函数并正在尝试以下操作:

  fieldset: yup
    .object()
    .shape({
      phone: yup.bool(),
      email: yup.bool(),
      push: yup.bool(),
    })
    .required()
    .test(
      "comms-Selected",
      "Please specify at least one means to be contacted",
      (value) =>
        value.phone === true || value.email === true || value.push === true
    ),

我不确定这个验证器函数的语法,yup 文档让我头晕目眩。我知道它不起作用,因为我可以提交所有字段都未选中的表单。有人可以帮助我了解如何正确编写此自定义验证器吗?

发现这个问题,修改以满足您的需求 https://github.com/jquense/yup/issues/72

let SignupSchema = yup.object().shape({
  firstName: yup.string().required(),
  age: yup.number().required().positive().integer(),
  // website: yup.string().url(),
  choice1: yup.boolean(),
  choice2: yup.boolean(),
  choice3: yup.boolean()
});

// extend the existing schema for the choice validation
SignupSchema = SignupSchema.test(
  // this test is added additional to any other (build-in) tests
  "choicesTest",
  null, 
  (obj) => {
    // only testing the checkboxes here
    if (obj.choice1 || obj.choice2 || obj.choice3) {
      return true; // everything is fine
    }

    return new yup.ValidationError("Check at least one ", null, "choices");
  }
);

HTML

<div>
  <label style={{ lineHeight: 1, padding: 0, margin: 0 }}>
    Check - Choice 1
    <input type="checkbox" name="choice1" ref={register} />
  </label>
  <label style={{ lineHeight: 1, padding: 0, margin: 0 }}>
    Check - Choice 2
    <input type="checkbox" name="choice2" ref={register} />
  </label>
  <label style={{ lineHeight: 1, padding: 0, margin: 0 }}>
    Check - Choice 3
    <input type="checkbox" name="choice3" ref={register} />
  </label>
  {errors.choices && <p>{errors.choices.message}</p>}
</div>

感谢您的回复和解答。我发现了问题。我的语法很好。结果是在醉酒的昏迷中,我昨天晚上不小心将 react-hook-form 更新为更新的版本,对于更新的版本,有第二个依赖项和用于声明 yup 解析器的语法略有不同。瞧,添加依赖项并更改代码中的一行导致我上面的原始代码工作。对于同一条船上的任何人,请查阅 react-hook-form 文档!他们与模式验证器的集成发生了微小的变化!

react-hook-form 的原始行和依赖关系 5.x.x:

import { useForm } from "react-hook-form";
import * as yup from "yup";

  const { register, handleSubmit, setValue, errors } = useForm({
    validationSchema: ContactSchema, //name of your schema goes here
  });

针对 react-hook-form 进行了修改 6.x.x:

import { useForm } from "react-hook-form";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";

  const { register, handleSubmit, setValue, errors } = useForm({
    resolver: yupResolver(ContactSchema),
  });