【问题标题】:How To add a min and max length verification to a number field?如何向数字字段添加最小和最大长度验证?
【发布时间】:2017-08-20 23:30:22
【问题描述】:

我有一个数字字段的代码:

<label for="Phone">Phone Number</label><br/>
<input id="Phone" name="Phone"class="form-control" type="tel"         pattern="^\d{3}\d{3}\d{4}$" maxlength="10"  minlength="10"  required >

但是,这不仅限于数字,而且只有一种格式有效,我想做这样的事情:

<input name="Phone" type="number"  class="form-control"     placeholder="Phone Number" maxlength="10"  minlength="10"     required="required"/>

并且该代码不限制最大和最小长度! 我如何让长度起作用?

【问题讨论】:

    标签: javascript html forms input


    【解决方案1】:

    来自mozilla docs

    如果 type 属性的值是 text、email、search、password、tel 或 url,则此属性指定用户可以输入的最小字符数(以 Unicode 代码点表示)。对于其他控件类型,将被忽略。

    这意味着对于数字输入,此属性无法按预期工作。

    这是您可以定义自己的长度验证器的一种方法(当然您可以编写自己的;)):

    numberInput.addEventListener('input', function() {
        this.value = this.value.substring(0, MAX_LENGTH);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-09
      • 1970-01-01
      • 2010-11-30
      • 1970-01-01
      相关资源
      最近更新 更多