【问题标题】:React form hooks How to validate select option反应表单钩子如何验证选择选项
【发布时间】:2020-10-15 20:57:24
【问题描述】:

我正在使用到达挂钩并验证我正在使用react-hook-form 的表单字段,因为它是目前最好的选择

所以要验证我的正常输入字段,我只是在做 ref={register({ required: true })} 然后提交它正在检查错误,因为我正在从 react-hook-form 导入错误

但是当我对选择字段做同样的事情时,它不会检查错误对象

这就是我正在做的事情

<label htmlFor="func" className="form_label">
      Select function
    </label>
    <select name="func" ref={register({ required: true })}>
      <option selected disabled>
        Select function
      </option>
      <option value="5">Function 2</option>
      <option value="6">Function 3</option>
    </select>
    {errors.func && (
      <div>
        <span>Function is required</span>
      </div>
    )}

我不知道我错过了什么

我的实际代码是动态数据

所以我是这样循环的

<Form.Control as="select" custom>
                    <option disabled selected>Select role</option>
                    {loading === false &&
                    data.get_roles.map((li) => (
                    <option value={li.user_type_id}> 
                    {li.user_type}</option>
        ))}
            </Form.Control>

React hook form

【问题讨论】:

标签: javascript reactjs react-hooks react-hook-form


【解决方案1】:

试试这个代码。我试过了,效果很好:

<label htmlFor="func" className="form_label">
  Select function
</label>
<select name="func" 
  ref={register({
     required: "select one option"
  })}>
  <option value=""></option>
  <option value="5">Function 2</option>
  <option value="6">Function 3</option>
</select>
{errors.func && <p style={{color:'red'}}> {errors.func.message}</p> }

【讨论】:

  • 它不起作用,请您分享代码沙箱
  • 希望对您有所帮助code sandbox
猜你喜欢
  • 2021-09-21
  • 2021-09-21
  • 1970-01-01
  • 2021-03-20
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 2023-01-17
  • 1970-01-01
相关资源
最近更新 更多