<input>字段的minlength属性似乎不起作用。
在HTML中是否有其他属性可以帮助我设置字段值的最小长度?
<input>字段的minlength属性似乎不起作用。
在HTML中是否有其他属性可以帮助我设置字段值的最小长度?
当前回答
新版本:
它扩展了使用(文本区域和输入)并修复了错误。
// 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);
}
}
}
其他回答
我注意到,有时在Chrome中,当自动填充打开时,字段是由自动填充浏览器内置方法填写的,它绕过了最小长度验证规则,所以在这种情况下,你必须通过以下属性禁用自动填充:
autocomplete = "结束"
<input autocomplete="new-password" name="password" id="password" type="password" placeholder="Password" maxlength="12" minlength="6" required />
我使用maxlength和minlength,无论是否需要,它对我来说都非常适合HTML5。
<输入id=“passcode”类型=“minlength”密码=“8”,maxlength=“10”>
`
我写了这个JavaScript代码,[minlength.js]:
window.onload = function() {
function testaFunction(evt) {
var elementos = this.elements;
for (var j = 0; j < elementos.length; j++) {
if (elementos[j].tagName == "TEXTAREA" && elementos[j].hasAttribute("minlength")) {
if (elementos[j].value.length < elementos[j].getAttribute("minlength")) {
alert("The textarea control must be at least " + elementos[j].getAttribute("minlength") + " characters.");
evt.preventDefault();
};
}
}
}
var forms = document.getElementsByTagName("form");
for(var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', testaFunction, true);
}
}
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>
同时添加最大值和最小值。您可以指定允许的值的范围:
<input type="number" min="1" max="999" />