function validate() {
var myName = document.getElementById("inputName");
var myEmail = document.getElementById("inputEmail");
var filter = /^[_a-z0-9]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i;
var myMessage = document.getElementById("inputMessage");
var isValid = true;
if(myName.value == "") {
var myNameError = document.getElementById("inputNameError");
myNameError.innerHTML = "Please provide your name.";
isValid = false;
}
if (!filter.test(myEmail.value)) {
var myEmailError = document.getElementById("inputEmailError");
myEmailError.innerHTML="Please provide your email.";
isValid = false;
}
if(myMessage.value == "") {
var myMessageError = document.getElementById("inputMessageError");
myMessageError.innerHTML = "Please provide your message.";
isValid = false;
}
return isValid;
}
答案 0 :(得分:1)
您可以尝试jQuery验证:http://jqueryvalidation.org/documentation/
它可以减轻你的许多验证问题...
答案 1 :(得分:0)
如果我对你的问题的理解是正确的。以下是您的方案:
原因是因为每个输入字段有1个错误分区(总共3个),并且当输入存在时它们不会被隐藏。您可以修改您的代码,如下所示:
function validate() {
var myName = document.getElementById("inputName");
var myEmail = document.getElementById("inputEmail");
var filter = /^[_a-z0-9]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i;
var myMessage = document.getElementById("inputMessage");
var isValid = true;
var myNameError = document.getElementById("inputNameError");
var myEmailError = document.getElementById("inputEmailError");
var myMessageError = document.getElementById("inputMessageError");
//Initially hide all previous error messages.
myNameError.className="hidden";
myEmailError.className="hidden";
myMessageError.className="hidden";
if(myName.value == "") {
myNameError.className="visible";//make error message div visible only on error.
myNameError.innerHTML = "Please provide your name.";
isValid = false;
}
if (!filter.test(myEmail.value)) {
myEmailError.className="visible";//make error message div visible only on error.
myEmailError.innerHTML="Please provide your email.";
isValid = false;
}
if(myMessage.value == "") {
myMessageError.className="visible";//make error message div visible only on error.
myMessageError.innerHTML = "Please provide your message.";
isValid = false;
}
return isValid;
}
<强> CSS 强>
.hidden {display: none;}
.visible {display: block;}
编辑根据评论添加fiddle链接。