<input>字段的minlength属性似乎不起作用。
在HTML中是否有其他属性可以帮助我设置字段值的最小长度?
<input>字段的minlength属性似乎不起作用。
在HTML中是否有其他属性可以帮助我设置字段值的最小长度?
当前回答
现在HTML5规范中有一个minlength属性,以及有效性。tooShort接口。
现在所有现代浏览器的最新版本都启用了这两个功能。具体操作请参见https://caniuse.com/#search=minlength。
其他回答
您可以使用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)">
我注意到,有时在Chrome中,当自动填充打开时,字段是由自动填充浏览器内置方法填写的,它绕过了最小长度验证规则,所以在这种情况下,你必须通过以下属性禁用自动填充:
autocomplete = "结束"
<input autocomplete="new-password" name="password" id="password" type="password" placeholder="Password" maxlength="12" minlength="6" required />
不是HTML5,但无论如何都很实用:如果你碰巧使用AngularJS,你可以在输入和文本区域都使用ng-minlength(或data-ng-minlength)。看看这个Plunk。
maxlength最聪明的方法
$(“html”)。On ("keydown keyup change", "input", function(){ var最大长度= $(这).attr(最大长度); 如果(最大长度){ = $ var值(这).val (); 如果(value.length < =最大长度){ (美元).attr(“v”,价值); } 其他{ ((这).val美元(这).attr (' v ')); } } }); < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < /脚本> <input type="text" maxlength="10">
我使用了最大值和最小值,这对我来说很有效,但我不确定这是否是一种编码方法。
<input type="text" maxlength="13" name ="idnumber" class="form-control" minlength="13" required>