【问题标题】:Validation for array of fields using react hook form使用反应钩子形式验证字段数组
【发布时间】:2020-11-26 17:36:39
【问题描述】:

我想向输入字段添加验证。我正在使用反应钩子形式。 验证应该就像字段的总和应该是 100。如果任何字段的总和大于或小于 100,它应该在输入字段(最后编辑的字段)显示错误。

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

谢谢??????

【问题讨论】:

  • 感谢沙盒,但您在 handleSubmit 中的尝试在哪里?你能用const handleSubmit = (form) => { console.log('form', form.questions) }查看值吗,你可以把它们加起来,如果大于或小于100,就会显示错误。

标签: reactjs react-hook-form react-forms


【解决方案1】:

你为什么不使用范围?您可以将最小值设置为 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


【讨论】:

    【解决方案2】:

    此 handleSubmit 函数将获取您的所有字段,获取您的值,添加它们并为您提供总数。您可以在 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.
          }
           
      };
    

    sandbox

    react-use-form error handling

    【讨论】:

      【解决方案3】:

      你只需要使用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 对象将如下所示:

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

      然后您可以使用{ errors.questions?.message } 显示错误。

      【讨论】:

      • codesandbox.io/s/lingering-shadow-0cxxo?file=/src/App.js同样的方法,但是错误显示不正确..你能看看吗?
      • 看起来验证实际上正在运行并消除错误,但react-hook-formerror 对象不是。我怀疑这与渲染隔离有关,但不知何故,它没有正确检查 Yup 错误对象的更新。也许你应该在react-hook-form 上打开一个问题。
      猜你喜欢
      • 1970-01-01
      • 2021-03-23
      • 2021-03-24
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 2018-12-28
      相关资源
      最近更新 更多