首页 > 解决方案 > react-hook-form 为什么数字输入类型忽略maxLength?

问题描述

我正在使用 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"
        />

标签: javascriptreactjsformsreact-hook-form

解决方案


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

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

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

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

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

推荐阅读