如何将最小和最大长度验证添加到数字字段? [英] How To add a min and max length verification to a number field?

查看:84
本文介绍了如何将最小和最大长度验证添加到数字字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the code for a number field:

<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 >

然而,这并不仅限于数字,只有一种格式有效我想做的事情如下:

However that doesn't limit to only numbers and only one format works i want to do something like:

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

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

and that code does not limit the max and min lengths! How do i get the lengths to work?

推荐答案

来自 mozilla docs


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

If the value of the type attribute is text, email, search, password, tel, or url, this attribute specifies the minimum number of characters (in Unicode code points) that the user can enter. For other control types, it is ignored.

这意味着此属性对于数字输入不起作用。

That means that this attribute does not work as expected for a number input.

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

Here's one way you can define your own length-validator (of course you can write your own ;) ):

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

这篇关于如何将最小和最大长度验证添加到数字字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆