<input>字段的minlength属性似乎不起作用。
在HTML中是否有其他属性可以帮助我设置字段值的最小长度?
<input>字段的minlength属性似乎不起作用。
在HTML中是否有其他属性可以帮助我设置字段值的最小长度?
当前回答
这是html5的唯一解决方案(如果你想要minlength 5, maxlength 10字符验证)
http://jsfiddle.net/xhqsB/102/
< >形式 <输入模式= "。{5 10}" > <input type="submit" value="Check"></input> > < /形式
其他回答
minLength属性(不像maxLength)在HTML5中并不存在。但是,如果字段包含少于x个字符,则有一些方法可以验证字段。
一个使用jQuery的例子:http://docs.jquery.com/Plugins/Validation/Methods/minlength
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<script type="text/javascript">
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});;
</script>
<script>
$(document).ready(function(){
$("#myform").validate({
rules: {
field: {
required: true,
minlength: 3
}
}
});
});
</script>
</head>
<body>
<form id="myform">
<label for="field">Required, Minimum length 3: </label>
<input class="left" id="field" name="field" />
<br/>
<input type="submit" value="Validate!" />
</form>
</body>
</html>
看到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">
我注意到,有时在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。
同时添加最大值和最小值。您可以指定允许的值的范围:
<input type="number" min="1" max="999" />