我用 if else 条件编写了一个简单的纯 javascript 表单验证。验证功能检查用户输入和输入字段中输入的字符数。
如果焦点输入字段为空,则会在焦点输入字段下方弹出一条错误消息,如果有输入,它将检查其长度,直到满足条件。
我想知道的是为什么 javascript 代码只验证第一个输入字段而不验证其余部分?
请不要发布任何 javascript 验证库,因为我正在编写自己的验证函数以用于学习目的,包括 bassistance jquery 插件、jquery 验证表单等。
Javascript:
function validateForm(){
var firstname = document.getElementById("firstname"),
lastname = document.getElementById("lastname"),
email = document.getElementById("email"),
firstnameLength = firstname.value.length,
checkLengthLast = lastname.value.length;
if(firstname == isEmpty){
errorFirstname();
firstname.focus();
return false;
} else if(firstname.value != isEmpty){
checkLengthFirst();
firstname.focus();
return false;
} else if(lastname.value == isEmpty){
errorLastname();
lastname.focus();
return false;
} else if (lastname.value != isEmpty){
checkLastName();
lastname.focus();
return false
} else if(email.value == isEmpty){
alert("Please fill in your email");
document.PersonDetails.email.focus();
return false;
} else {
return true;
}
function isEmpty(){
this.value == 0;
}
function errorFirstname(){
var errorpara = document.createElement("p");
errorpara.innerHTML = "Please fill in your firstname";
firstname.parentNode.insertBefore(errorpara, firstname.nextSibling);
setInterval(function (){
errorpara.style.display = "none";
}, 2000);
return false;
}
function checkLengthFirst(){
if(firstnameLength <= 2){
var errorpara = document.createElement("p");
errorpara.innerHTML = "Name must be more than 2 characters";
firstname.parentNode.insertBefore(errorpara, firstname.nextSibling);
setInterval(function (){
errorpara.style.display = "none";
}, 2000);
}
return false;
}
function errorLastname(){
var errorpara = document.createElement("p");
errorpara.innerHTML = "Please fill in your lastname";
setInterval(function (){
lastname.parentNode.insertBefore(errorpara, lastname.nextSibling);
}, 2000);
return false;
}
function checkLengthLast(){
if(lastnameLength <= 2){
var errorpara = document.createElement("p");
errorpara.innerHTML = "Name must be more than 2 characters";
lastname.parentNode.insertBefore(errorpara, lastname.nextSibling);
setInterval(function (){
errorpara.style.display = "none";
}, 2000);
}
return false;
}
return true;
}
的HTML:
<form id="register" name="PersonDetails" onsubmit="return validateForm();" method="post" action="">
<div>
<label>Firstname :</label>
<label>Lastname :</label>
<label>Email :</label>
</div>
<div>
<input type="text" name="firstname" id="firstname" value="" />
<input type="text" name="lastname" id="lastname" value="" />
<input type="text" name="email" id="email" value="" />
<input class="submit" type="submit" name="submit"/>
</div>
</form>
预先感谢您的帮助。