我正在处理一个带有一些可选字段的表单,只有在输入时才需要验证这些字段.然而,即使没有输入,react hook form也会返回一个验证错误.我也试着设置:

required: {
value: false,
message: "This field is not required"
}

但即使未输入任何输入,它仍会返回验证错误.

下面是仅在输入时才需要验证的其中一个字段的代码片段.

<div className={styles.formInputFile}>
          <label htmlFor="ref_letter">
            Reference Letter (For Doctorate and Diploma Courses)
          </label>
          <Controller
            control={control}
            name={"reference_letter"}
            rules={{
            required: {
              value: refLetterRequired();
              message: "This is field is required",
},
              validate: {
                fileSize: (file) => {
                  return (
                    file?.size < 2000100 &&
                    "File size shouldn't be more than 2MB!"
                  );
                },
                acceptedFormats: (file) => {
                  return (
                    ["image/png", "image/jpeg", "application/pdf"].includes(
                      file?.type
                    ) || "Only JPEG, PNG and PDF files are accepted!"
                  );
                },
              },
            }}
            render={({ field: { value, onChange, ...field } }) => {
              return (
                <input
                  {...field}
                  value={value?.fileName}
                  onChange={(event) => {
                    onChange(event.target.files[0]);
                  }}
                  type="file"
                  id="rererence_letter"
                  accept=".png, .jpeg, .pdf"
                />
              );
            }}
          />
          <p>{errors.reference_letter?.message}</p>
        </div>

第二次编辑:

该表单是一个多步骤表单,在用户可以移动到下一步之前,每一步都需要没有错误.下面是控制该字段的所有代码片段.即使有正确的输入并且该字段不是必填项,我也不断收到验证错误.

  const certCourses = [
    "Certificate in D",
    "Certificate in t",
    "certificate in H",
    "Certificate in P",
    "Certificate in Pus",
    "Certificate Hec Diseases",
    "Certificate in He",
  ];

  const refLetterRequired = () => {
    for (let i = 0; i < certCourses.length; i++) {
      if (watch("proposed_course") === certCourses[i]) return false;
    }
    return true;
  };

期望值.如果所选的"Proposed_Course"不在"certCourses"中,则该字段应为必填字段,否则该字段不应为必填字段.

Code controlling "next" button of the multi-step form:

  const next = async (e) => {
    const field = steps[currentStep].fields;
    const output = await trigger(field);
    if (!output) return;
    setValue(e.target.name, e.target.value, {
      shouldDirty: true,
      shouldValidate: true,
      shouldTouch: true,
    });
    setCurrentStep(currentStep + 1);
  };

const [currentStep, setCurrentStep] = useState(0);




const steps = [
  {
    name: "step 1",
    description: "Personal Information",
    fields: [
      "title",
      "surname",
      "first_name",
      "gender",
      "middle_name",
      "maiden_name",
      "religion",
      "birth_date",
      "nationality",
      "state_of_origin",
      "disability",
    ],
  },
  {
    name: "step 2",
    description: "Next of Kin Information",
    fields: [
      "next_of_kin_name",
      "next_of_kin_address",
      "next_of_kin_relationship",
      "next_of_kin_phone",
      "next_of_kin_occupation",
    ],
  },
}

推荐答案

You can check if the field value is empty or equal to the default value and return "true"(i.e. indicate that the field passed validation) in that case.
For example

fileSize: (file) => {
  if (file === null) return true;
  return (
    file?.size < 2000100 &&
    "File size shouldn't be more than 2MB!"
   );
},

在react 挂钩形式的GitHub https://github.com/react-hook-form/react-hook-form/issues/1781中有一个关于这一问题的未决问题

Reactjs相关问答推荐

在Reaction中单击时,按钮未按预期工作

如何在取数后添加新数据,并在页面上保存旧数据?

使用`Link`包装`tr`标记会在Next.js中产生水合错误14

梅X折线图无响应

无法将react 路由状态从路由传递给子组件

安装使用环境的BIT组件的依赖项

状态更改是否卸载功能组件

蚂蚁 Select .列表弹出窗口不会';有时不会出现

使用以Jest 的方式返回 Promise 的方法来模拟可构造的 API 类时出现问题

Chart.js如何go 除边框

.populate() 方法在 mongodb 中不起作用

PWA:注册事件侦听器不会被触发

如何根据用户在react.js中的 Select , Select 多个心形图标?

redux 工具包使用中间件构建器函数时,必须返回一个中间件数组

我正在通过 API(有效)从 MongoDB 传递数据.可视化但我不断收到此 TypeError: Cannot convert undefined or null to object

一周前刚开始学习React,一直在调试为什么输入框在每次输入后都没有焦点

react 事件顺序

setState 改变对象引用

react 页面更新

NextJs - 如何从站点 map 生成器中删除重复的 URL?