<input>字段的minlength属性似乎不起作用。
在HTML中是否有其他属性可以帮助我设置字段值的最小长度?
<input>字段的minlength属性似乎不起作用。
在HTML中是否有其他属性可以帮助我设置字段值的最小长度?
当前回答
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
通过使用模式。
其他回答
我的解决方案textarea使用jQuery和结合HTML5需要验证,以检查最小长度。
minlength.js
$(document).ready(function(){
$('form textarea[minlength]').on('keyup', function(){
e_len = $(this).val().trim().length
e_min_len = Number($(this).attr('minlength'))
message = e_min_len <= e_len ? '' : e_min_len + ' characters minimum'
this.setCustomValidity(message)
})
})
HTML
<form action="">
<textarea name="test_min_length" id="" cols="30" rows="10" minlength="10"></textarea>
</form>
这是html5的唯一解决方案(如果你想要minlength 5, maxlength 10字符验证)
http://jsfiddle.net/xhqsB/102/
< >形式 <输入模式= "。{5 10}" > <input type="submit" value="Check"></input> > < /形式
你可以在输入标签中使用minlength,或者你可以regex pattern来检查字符的数量,甚至你可以输入并检查字符的长度,然后你可以根据你的要求进行限制。
您可以使用pattern属性。还需要必需的属性,否则带有空值的输入字段将被排除在约束验证之外。
<input pattern=".{3,}" required title="3 characters minimum">
<input pattern=".{5,10}" required title="5 to 10 characters">
如果你想创建一个选项来使用“空,或最小长度”的模式,你可以这样做:
<input pattern=".{0}|.{5,10}" required title="Either 0 OR (5 to 10 chars)">
<input pattern=".{0}|.{8,}" required title="Either 0 OR (8 chars minimum)">
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
通过使用模式。