【问题标题】:react-hook-form Why does number input type ignore maxLength?react-hook-form 为什么数字输入类型忽略maxLength?
【发布时间】:2021-05-03 21:07:31
【问题描述】:

我正在使用 react-hook-form 创建一个 4 位数字的输入,这不会让用户输入字母或字符,但它忽略了 maxLength 值。我能够得到一个只允许数字的输入,但我无法限制长度。

这是我的输入:

     <input
          id="fourNumbers"
          required
          type="number"
          name="fourNumbers"
          ref={register({ required: true, pattern: /[0-9]{4}/ })}
          placeholder="0000"
          maxLength="4"
          minLength="4"
        />

【问题讨论】:

    标签: javascript reactjs forms react-hook-form


    【解决方案1】:

    取自https://stackoverflow.com/a/9555196/1772933

    对 type="number" 的输入使用 max 属性。它将指定您可以插入的最大可能数字

      <input type="number" max="9999" />
    

    如果同时添加最大值和最小值,则可以指定允许值的范围:

      <input type="number" min="1000" max="9999" />
    

    【讨论】:

      【解决方案2】:

      尝试像这样在寄存器中使用它:

      <input 
           ref={register({ required: true, pattern: /[0-9]{4}/, minLength: 4, 
                                                           maxLength: 4 })}
      />
      

      可能会显示错误。

      【讨论】:

        猜你喜欢
        • 2021-12-09
        • 2022-01-23
        • 2022-07-30
        • 1970-01-01
        • 2023-03-17
        • 2015-08-12
        • 2013-09-01
        • 2022-11-17
        相关资源
        最近更新 更多