React Form Hooks如何验证选择选项

时间:2020-06-25 11:53:45

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

我正在使用覆盖范围钩子并验证我的表单字段,因此我正在使用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

1 个答案:

答案 0 :(得分: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> }