<input>字段的minlength属性似乎不起作用。
在HTML中是否有其他属性可以帮助我设置字段值的最小长度?
<input>字段的minlength属性似乎不起作用。
在HTML中是否有其他属性可以帮助我设置字段值的最小长度?
当前回答
这是html5的唯一解决方案(如果你想要minlength 5, maxlength 10字符验证)
http://jsfiddle.net/xhqsB/102/
< >形式 <输入模式= "。{5 10}" > <input type="submit" value="Check"></input> > < /形式
其他回答
不是HTML5,但无论如何都很实用:如果你碰巧使用AngularJS,你可以在输入和文本区域都使用ng-minlength(或data-ng-minlength)。看看这个Plunk。
看到http://caniuse.com/搜索=最小长度。某些浏览器可能不支持此属性。
如果"type"的值是其中之一:
文本,电子邮件,搜索,密码,电话或URL(警告:不包括数字|没有浏览器支持“电话”现在- 2017.10)
使用minlength(/ maxlength)属性。它指定最小字符数。
例如,
<input type="text" minlength="11" maxlength="11" pattern="[0-9]*" placeholder="input your phone number">
或者使用"pattern"属性:
<input type="text" pattern="[0-9]{11}" placeholder="input your phone number">
如果“type”是number,虽然不支持minlength(/ maxlength),但可以使用min(/ max)属性来代替它。
例如,
<input type="number" min="100" max="999" placeholder="input a three-digit number">
Minlength属性现在在大多数浏览器中得到广泛支持。
<input type="text" minlength="2" required>
但是,与HTML5的其他功能一样,IE11在这个全景图中是缺失的。所以,如果你有一个广泛的IE11用户基础,考虑使用模式HTML5属性,几乎所有的浏览器(包括IE11)都支持它。
为了有一个漂亮和统一的实现,可能是可扩展的或动态的(基于生成HTML的框架),我会投票给pattern属性:
<input type="text" pattern=".{2,}" required>
在使用模式时,仍然存在一个小的可用性问题。在使用pattern时,用户将看到一条非直观的(非常通用的)错误/警告消息。查看jsfiddle或下面:
在每个表单中输入1个字符并按submit</h3> < / h2 > <形式action = " # " > Input with minlength: < Input type="text" minlength="2" required name="i1"> <input type="submit" value=" submit" > > < /形式 < br > <形式action = " # " > Input with patern: < Input type="text" pattern="。{2,}" required name="i1"> <input type="submit" value=" submit" > > < /形式
例如,在Chrome中(但在大多数浏览器中类似),你会得到以下错误消息:
Please lengthen this text to 2 characters or more (you are currently using 1 character)
通过使用minlength和
Please match the format requested
通过使用模式。
我注意到,有时在Chrome中,当自动填充打开时,字段是由自动填充浏览器内置方法填写的,它绕过了最小长度验证规则,所以在这种情况下,你必须通过以下属性禁用自动填充:
autocomplete = "结束"
<input autocomplete="new-password" name="password" id="password" type="password" placeholder="Password" maxlength="12" minlength="6" required />
新版本:
它扩展了使用(文本区域和输入)并修复了错误。
// Author: Carlos Machado
// Version: 0.2
// Year: 2015
window.onload = function() {
function testFunction(evt) {
var items = this.elements;
for (var j = 0; j < items.length; j++) {
if ((items[j].tagName == "INPUT" || items[j].tagName == "TEXTAREA") && items[j].hasAttribute("minlength")) {
if (items[j].value.length < items[j].getAttribute("minlength") && items[j].value != "") {
items[j].setCustomValidity("The minimum number of characters is " + items[j].getAttribute("minlength") + ".");
items[j].focus();
evt.defaultPrevented;
return;
}
else {
items[j].setCustomValidity('');
}
}
}
}
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
var isChrome = !!window.chrome && !isOpera;
if(!isChrome) {
var forms = document.getElementsByTagName("form");
for(var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', testFunction,true);
forms[i].addEventListener('change', testFunction,true);
}
}
}