如何将 yup 与反应钩子形式一起使用?

How to use yup with react hook form?

我正在尝试使用 yup 在反应钩子表单上编写错误处理,但是当我想按照文档所述传递解析器时 (https://www.npmjs.com/package/@hookform/resolvers) 我收到此错误:

SyntaxError: Cannot use import statement outside a module

module.exports = require("@hookform/resolvers/yup");

我的验证模式:

const schema = Yup.object().shape({
  person: Yup.string()
    .min(3, "To pole jest za krótkie")
    .max(30, "To pole jest za długie")
    .required("To pole jest wymagane"),
});

React 钩子形式:

const {
    register,
    errors,
    handleSubmit,
    formState: { isSubmitting },
  } = useForm({ resolver: yupResolver(schema) });

进口:

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

Npm 版本:

"react-hook-form": "^6.15.1",
"yup": "^0.28.3"
"@hookform/resolvers": "^1.3.4",

这是 react-hook-form 中的错误。 https://github.com/react-hook-form/resolvers/issues/107

如果您使用 react-hook-form v6,目前唯一的解决方法是将 @hookform/resolvers 降级到 1.3.0,或者使用测试版 2.0.0-beta.3。较新的版本仅支持 react-hook-form v7.