簡體   English   中英

使用反應掛鈎形式驗證字段數組

[英]Validation for array of fields using react hook form

我想向輸入字段添加驗證。 我正在使用反應掛鈎形式。 驗證應該像字段的總和應該是 100。如果任何字段使總和大於或小於 100,它應該在輸入字段(最后編輯的字段)中顯示錯誤。

沙盒 url: https://codesandbox.io/s/distracted-elion-z2wob?file=/src/App.js

謝謝

react-hook-form v7.34.0中最近有一個新功能,它提供了這種開箱即用的驗證......

您在定義字段數組時設置它

在您的情況下,您可以在自定義驗證 function 中運行字段總和 == 100 的檢查

useFieldArray({
  name: 'test',
  rules: {
    validate: (fieldArrayValues) => {
      // check that sum of all fields == 100
    },
  }
})

然后你檢查/使用錯誤

errors?.test?.root?.message

有關更多詳細信息,請參見此處...

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

你為什么不使用范圍? 您可以將最小值設置為 0,最大值設置為 100-current,這將阻止用戶設置任何高於 100 的值。關於 100 以下的值,您可以手動檢查。


<input type="range" min="0" max={100-currentTotal} step={1}/>
{currentTotal< 100 && lastEdited? "error the sum should be equal to 100" : null}
// I used 1 as the step, but you can set any value


這個句柄提交 function 將獲取您的所有字段,獲取您的值,添加它們並為您提供總數。 您可以在 if-else 語句中處理錯誤。

 const handleOnSubmit = (form) => {
       console.log('form fields', form.questions)
       let data = form.questions.map( x => x.percentage ).reduce((a,b) => a + b);

      if ( data !== 100) {
        console.log('total', data , ' is not 100');
        //error handling here.
      }
       
  };

沙盒

react-use-form 錯誤處理<- 錯誤處理代碼和示例在這里。

您只需要使用 Yup 的test()方法來驗證總數:

resolver: yupResolver(
  object().shape({
    questions: array()
      .of(
        object().shape({
          percentage: number().typeError('Wrong type.').required('Required.')
        })
      )
      .required()
      .test(
        'sum',
        'The total should be less or equal than 100.',
        (questions = []) => {
          const total = questions.reduce((total, question) => {
            return total + (question.percentage || 0);
          }, 0);

          return total <= 100;
        }
      )
  })
),

如果驗證失敗, errors object 將如下所示:

{
  "questions": {
    "message": "The total should be less or equal than 100.",
    "type": "sum"
  }
}

然后,您可以使用{ errors.questions?.message }顯示錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM