網站搜尋

javascript - 我如何在 React Hook Form 中使用 useFieldArray hook 驗證陣列欄位?


我有一些關於 React Hook Form 以及它驗證陣列欄位方式的問題。

我在組件掛載時試圖使用 useEffect 來註冊陣列欄位,但後來我注意到有一個 useFieldArray 鉤子,它不會掛載任何東西,直到你附加一個欄位。

所以我有這個:

  const { fields, append, remove } = useFieldArray<FieldValues>({
    name: `logic.${index}.questions` as 'logic.0.questions',
  })

而我能看到該欄位,直到選取元素觸發 onChange 事件為止。

<Select onChange={e => append({ id: e.target.value }) }>...</Select>

根據我附加的內容,useFieldArray 的 fields 值會開始增加長度,因此我可以根據這個來渲染新的內容,例如:

<Box>
  { fields.map((field) => <Text key={field.id}>{ field.id }</Text> )}
</Box>

所以例如這裡 https://codesandbox.io/s/react-hook-form-usefieldarray-nested-arrays-x7btr?file=/src/index.js

在提交時,你如何驗證陣列是否有正數長度(> 0)並顯示錯誤訊息。

我注意到當欄位只是物件時,你可以輕鬆做到這一點,但例如我該怎麼做來驗證我在這裡使用 useFieldArray 的程式碼,如果 fields 的長度大於 0 則提交表單,否則顯示錯誤(?)

答案#1

在 react-hook-form v7.34.0 中有一個最近的新功能,可以開箱即用地提供這種類型的驗證...

當你定義字段陣列時,你設置它

在你的情況下,你想要規則 required: true

useFieldArray({
  name: 'test',
  rules: {
    required: true,
  }
})

然後你檢查/使用錯誤,如此

errors?.test?.root?.message

注意,還有另一個變體允許你在必填檢查失敗時提供自訂錯誤訊息...

例如

rules: {
  required: {
    value: true,
    message: "At least one is required",
  }
}

詳情請見此處...

https://react-hook-form.com/api/usefieldarray/

https://github.com/react-hook-form/react-hook-form/issues/6879

https://github.com/react-hook-form/react-hook-form/pull/8562

答案#2

這可能不是你正確尋找的解決方案,但這是我如何解決的。我有一個類似於你分享的 codesandbox 的設置,只是沒有嵌套字段,並且包含一個 Remove 按鈕,點擊時會移除最後一個 fieldArray 元素:

<button onClick={() => controlledFields.length > 1 ? remove(controlledFields.length - 1) : null}>
  Remove
</button>

這非常重要,因為我在 fieldArray.map() 中使用了 required:true 驗證,強制使用者移除空的輸入欄位,並至少填寫第一個。在你提供的範例中,這將是

<Box>
  { 
    fields.map((field) => (
      <>
      <Text 
        key={field.id}
        {...register(`fields.${index}`, {required:true})}
       >
      { field.id }
      </Text> 
      { errors.fields?.[index] && 
          <p> { index === 0 ? "Must select at least one" : "Remove empty fields if unused" } </p>
      }
      </>
    ))
  }
</Box>