<input>字段的minlength属性似乎不起作用。

在HTML中是否有其他属性可以帮助我设置字段值的最小长度?


当前回答

是的,在那儿。就像maxlength。W3.org文档: http://www.w3.org/TR/html5/forms.html#attr-fe-minlength

如果minlength不起作用,可以使用@Pumbaa80提到的模式属性作为输入标记。

文本区域: 用于设置最大值;使用maxlength和min转到这个链接。

你会发现这里有最大值和最小值。

其他回答

这是html5的唯一解决方案(如果你想要minlength 5, maxlength 10字符验证)

http://jsfiddle.net/xhqsB/102/

< >形式 <输入模式= "。{5 10}" > <input type="submit" value="Check"></input> > < /形式

您可以使用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)">

如果需要这种行为,总是在输入字段上显示一个小前缀,否则用户不能删除前缀:

   // prefix="prefix_text"
   // If the user changes the prefix, restore the input with the prefix:
   if(document.getElementById('myInput').value.substring(0,prefix.length).localeCompare(prefix))
       document.getElementById('myInput').value = prefix;

现在HTML5规范中有一个minlength属性,以及有效性。tooShort接口。

现在所有现代浏览器的最新版本都启用了这两个功能。具体操作请参见https://caniuse.com/#search=minlength。

我的解决方案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>