我目前在表单验证方面存在问题。为简单起见,我现在只在这里验证名字和姓氏。
让我们说一个人不输入他们的名字或姓氏。它只显示错误消息"(请输入您的名字)"并且它没有显示"(请输入您的姓氏)"。
让我们说一个人输入他们的名字而不是他们的姓氏,然后显示"(请输入你的姓氏)"。
是否可以解决此问题,例如,如果某人没有输入他们的名字和姓氏,则会显示错误消息?
JavaScript的:
function validateAll() {
//Inputs
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
//Errors
var firstNameError = document.getElementById("firstNameError");
var lastNameError = document.getElementById("lastNameError");
if (
validateFirstName(firstName, firstNameError) == true &&
validateLastName(lastName, lastNameError) == true
) {
return true;
} else return false;
}
function validateFirstName(firstName, firstNameError) {
if (firstName == "") {
firstNameError.firstChild.nodeValue = "(Please Enter Your First Name)";
return false;
} else {
firstNameError.firstChild.nodeValue = "";
return true;
}
}
function validateLastName(lastName, lastNameError) {
if (lastName == "") {
lastNameError.firstChild.nodeValue = "(Please Enter Your Last Name)";
return false;
} else {
lastNameError.firstChild.nodeValue = "";
return true;
}
}
HTML:
<form name="registrationForm" id="registrationForm" onSubmit="return validateAll()" action="AddUserDetails">
<div class="form-group">
<label for="firstName">First Name</label>
<span id="firstNameError" class="error">*</span>
<input type="text" class="form-control" id="firstName" name="firstName">
</div>
<div class="form-group">
<label for="lastName">Second Name</label>
<span id="lastNameError" class="error">*</span>
<input type="text" class="form-control" id="lastName" name="lastName">
</div>
<div class="form-group">
<label for="phoneNumber">Phone Number</label>
<span id="phoneNumberError" class="error">*</span>
<input type="text" class="form-control" id="phoneNumber" name="phoneNumber">
</div>
<div class="form-group">
<label for="eMail">E-Mail</label>
<span id="eMailError" class="error">*</span>
<input type="text" class="form-control" id="eMail" name="eMail">
</div>
<div class="form-group">
<label for="eMailConfirmation">Confirm E-Mail</label>
<span id="eMailConfirmationError" class="error">*</span>
<input type="text" class="form-control" id="eMailConfirmation" name="eMailConfirmation">
</div>
<div class="form-group">
<label for="password">Password</label>
<span id="passwordError" class="error">*</span>
<input type="password" class="form-control" id="password" name="password">
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary"><i class="fa fa-user-md"></i> Register</button>
</div>
</form>
答案 0 :(得分:1)
由于您的代码的评估方式,这种情况正在发生。
validateFirstName(firstName, firstNameError) == true &&
validateLastName(lastName, lastNameError) == true
它将运行第一个函数,如果第一个名称未设置,则返回false。 false && (true || false)
将始终为假,因此它不会执行第二个功能。
正如您所看到的,当您在点击false
时立即运行此代码段时,它会停止执行(3是打印的最后一个数字)。使用或只执行第一个功能。
function test(bool, num){
console.log(num);
return bool;
}
var andResult = test(true, 1) &&
test(true, 2) &&
test(false, 3) &&
test(true,4);
console.log("&& result", andResult);
var orResult = test(true, 1) ||
test(true, 2) ||
test(false, 3) ||
test(true,4);
console.log("|| result", orResult);
&#13;
您可以运行每个函数并收集值:
var valFirstName = validateFirstName(firstName, firstNameError);
var valLastName = validateLastName(lastName, lastNameError);
return valFirstName && valLastName;
答案 1 :(得分:0)
问题在于javascript评估if语句的方式。因为你正在使用&amp;&amp;,如果第一个条件失败,它甚至不会费心去尝试执行第二个条件,因为无论结果如何,循环都不会运行((假&amp;&amp; true) == false)。 试试控制台在validateLastName函数中记录一些东西,你就会看到我在说什么;)
我无法找到有关所有这些爵士乐的更多信息,但我认为C ++编译器会做同样的事情。
答案 2 :(得分:-1)
所以你正在使用逻辑AND语句,而我的downvote是因为我使用了更接近但不太正确的逻辑OR语句。这是小型讲座。
逻辑AND表达式将执行语句的每个部分UNTIL遇到第一个false,此时整个表达式呈现为false并退出AND表达式。另一方面,逻辑OR语句将执行语句的每个部分,无论真实性或虚假性,然后评估表达式的最终布尔值。因此,使用AND,表达式将以第一个false结束。有两种方法可以解决这个问题。
首先,您可以按照建议进行操作,并将每个验证函数评估为变量,然后在AND语句中使用所有这些函数。这样做可确保您的所有表单字段都已经过验证。然后AND语句可以简单地确定表单是否有效。
var firstNameIsValid = validateFirstName(firstName, firstNameError),
lastNameIsValid = validateLastName(lastName, lastNameError);
if (firstNameIsValid && lastNameIsValid){
// Form is valid, proceed with processing
} else {
// Form is invalid because SOMETHING above was false. Do some other
// error handling.
}
其次,这是我所处的道路(但不是非常接近正确的反应)将其合并为一个OR语句,但不是检查字段是否有效,我们将检查它们& #39;重新无效。
if (!validateFirstName(firstName, firstNameError) || !validateLastName(lastName, lastNameError) ) {
// The above query is checking whether validate<fieldName> returned FALSE
// for every field. If any validate returns false, the entire form is
// invalid. Do any invalid form processing.
} else {
// The ELSE of the above if would only pass if every form field checked has
// in fact, passed the validity check. At this point, the form itself is
// valid and any processing for valid forms can happen.
}
现在,尽管如此,你还是为自己创造了一条丑陋的泥潭。此时,您只需要有效的名字和姓氏。但如果它们包含一个数字呢?如果你想要一个只有数字的字段怎么办?如果您想要一个既需要一个字段又一个电话号码怎么办?您将不得不为每个案例重新创建轮子。相反,如何创建一个可以推广到每个案例的函数呢?如果您遇到没有处理程序的情况,您可以创建它并将其添加到通用函数中,以便以后可用于任何其他表单元素。
var formEl = document.getElementById("my-custom-form");
formEl.querySelector("button").addEventListener("click", function(evt) {
evt.stopPropagation();
evt.preventDefault();
var isFormValid = [];
var validateThese = [{
fieldEl: formEl.querySelector("[name=firstName]"),
errorEl: formEl.querySelector("#firstNameError"),
checks: ["required", "alpha"]
}, {
fieldEl: formEl.querySelector("[name=lastName]"),
errorEl: formEl.querySelector("#lastNameError"),
checks: ["required", "alpha"]
}, {
fieldEl: formEl.querySelector("[name=phoneNumber]"),
errorEl: formEl.querySelector("#phoneNumberError"),
checks: ["numeric"]
}];
for (var i = 0, len = validateThese.length; i < len; i++) {
isFormValid[i] = validateField(validateThese[i]);
}
if (isFormValid.indexOf(false) != -1) {
// If there is ANY boolean false here, then one of the fields returned
// false, so the whole form is bad.
console.log("form is bad!");
} else {
// The entire isValid array is good, the form is good.
console.log("form is good!");
}
function validateField(checkThis) {
var isValid = [];
checkThis.errorEl.innerText = "";
for (var i = 0, len = checkThis.checks.length; i < len; i++) {
switch (checkThis.checks[i]) {
case "required":
isValid[i] = isRequired(checkThis.fieldEl);
if (!isValid[i]) {
checkThis.errorEl.innerHTML += "<br>Field is required!";
}
break;
case "alpha":
isValid[i] = isAlpha(checkThis.fieldEl);
if (!isValid[i]) {
checkThis.errorEl.innerHTML += "<br>Field must be alphabetic characters only!";
}
break;
case "numeric":
isValid[i] = isNumeric(checkThis.fieldEl);
if (!isValid[i]) {
checkThis.errorEl.innerHTML += "<br>Field must be numeric characters only!";
}
break;
case "alphanumeric":
isValid[i] = isAlphanumeric(checkThis.fieldEl);
if (!isValid[i]) {
checkThis.errorEl.innerHTML += "<br>Field must be alphanumeric only!";
}
break;
} // End switch
} // End for
if (isValid.indexOf(false) == -1) {
// isValid contains no false values, this field is ok.
return true;
} else {
// isValid contains at least one false. At least one test failed.
// field is bad.
return false;
}
} // End validateField()
/****
* Below are the actual validation functions. Given a field, they'll
* check that it conforms to a few types. At this pass, it'll look for
* required, alphabetic, numeric or alphanumeric.
*
****/
function isRequired(fieldEl) {
if (fieldEl.value.length > 0) {
return true;
} else {
return false;
}
} // end function isRequired();
function isAlpha(fieldEl) {
if (fieldEl.value.length > 0) {
if (/^[a-zA-Z]+$/.test(fieldEl.value)) {
return true;
} else {
return false;
}
} else {
return true;
}
} // end function isAlpha();
function isNumeric(fieldEl) {
if (fieldEl.value.length > 0) {
if (/^\d+$/.test(fieldEl.value)) {
return true;
} else {
return false;
}
} else {
return true;
}
} //end function isNumeric();
function isAlphanumeric(fieldEl) {
if (fieldEl.value.length > 0) {
if (/^[a-zA-Z0-9]+$/.test(fieldEl.value)) {
return true;
} else {
return false;
}
} else {
return true;
}
} // end function isAlphaumeric();
}) // end button click event listener
&#13;
<form id="my-custom-form" name="registrationForm">
<div class="form-group">
<label for="firstName">First Name</label>
<span id="firstNameError" class="error">*</span>
<input type="text" class="form-control" id="firstName" name="firstName" placeholder="required">
</div>
<div class="form-group">
<label for="lastName">Second Name</label>
<span id="lastNameError" class="error">*</span>
<input type="text" class="form-control" id="lastName" name="lastName" placeholder="required">
</div>
<div class="form-group">
<label for="phoneNumber">Phone Number</label>
<span id="phoneNumberError" class="error"></span>
<input type="text" class="form-control" id="phoneNumber" name="phoneNumber">
</div>
<div class="form-group">
<label for="eMail">E-Mail</label>
<span id="eMailError" class="error"></span>
<input type="text" class="form-control" id="eMail" name="eMail">
</div>
<div class="form-group">
<label for="eMailConfirmation">Confirm E-Mail</label>
<span id="eMailConfirmationError" class="error"></span>
<input type="text" class="form-control" id="eMailConfirmation" name="eMailConfirmation">
</div>
<div class="form-group">
<label for="password">Password</label>
<span id="passwordError" class="error"></span>
<input type="password" class="form-control" id="password" name="password">
</div>
<div class="text-center">
<button class="btn btn-primary"><i class="fa fa-user-md"></i> Register</button>
</div>
</form>
&#13;
上面的示例将遍历一个对象数组,每个对象都是一个字段el,一个错误el和一个要运行的测试数组。 &#34;要求&#34; test检查元素的值是否大于零,并且对于没有值或与其正则表达式匹配的值,alpha / numeric / alphanumeric测试返回true。后三者必须返回true才没有价值。