在用户输入时,我一直在寻找一种方法来验证我的表单。例如,我想要一个邮政编码字段。我希望用户在字段下方看到一条消息,说明他们已超出此字段的字符数限制,但在提交表单之前。怎么办呢?
使用此类代码:
ID
答案 0 :(得分:2)
试试这个:
<强> HTML 强>
<input type="text" name="first_name">
<div id="error">
My custom error
</div>
<强> CSS 强>
#error {
display: none;
}
#error.show {
display: block;
}
input {
color: #000000;
}
.invalid {
color: #FF0000;
}
<强> JS 强>
var input = document.querySelector('[name="first_name"]');
var error = document.getElementById('error');
input.addEventListener('keydown', function(){
// Whatever you want
if(this.value.length >= 10) {
this.classList.add('invalid');
// You can control style of your invalid input with .invalid
error.classList.add('show'); // Display your custom error
} else {
this.classList.remove('invalid');
error.classList.remove('show');
}
});
编辑说明:
var input
定位您的first_name输入
addEventListener
进行事件检测。通过参数&#39; keydown&#39;,JavaScript将听取按键。
classList
是一个操纵类的API(IE不支持)。