注意:
当你这样首先输入不足五位的时候是这样的
然后,你补足了五位以上,他仍然会提醒用户名为空。
解决办法是在每个输入框的属性里面加入一个这个, οnchange="setCustomValidity(''),意思是每次检测到变化的时候都先将历史的提醒清空。
添加之后:
继续添加发现不报错了。
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>表单校验</title>
</head>
<body>
<form action="#">
<!-- required属性是设置该框不能为空,如果为空会进行默认提醒 (请填写此字段,当然也可以在js中自己定义应该提醒的文字)-->
用户名:<input type="text" id="username" placeholder="请输入用户名" required onchange="setCustomValidity('')"/>
<br/>
密   码:<input type="password" id="passwd" placeholder="请输入密码" required onchange="setCustomValidity('')"/>
<br/>
<input type="submit" value="提交" onclick="check()"/>
</form>
<script>
function check(){
var name = document.querySelector("#username");
var passwd = document.querySelector('#passwd');
// if(name.value.trim().length<6 || passwd.value.trim().length<6){
// alert('用户名和密码长度必须大于5')
// }
// 对required属性里面提醒的字段进行自定义设置
if(!name.checkValidity()){
name.setCustomValidity("用户名不能为空");
}
if(name.value.trim().length<6 && name.value.trim().length>0){
name.setCustomValidity('没超过5位')
}
if(!passwd.checkValidity()){
passwd.setCustomValidity("密码不能为空");
}
console.log(name.value,passwd.value);
}
</script>
</body>
</html>