【发布时间】:2020-11-05 13:02:22
【问题描述】:
我试图在下面的 if 语句中嵌套另一个 if 语句以进行表单验证。基本上我希望 if 语句适用于所有字段(就像它目前所做的那样),但随后为某些字段提供额外的要求。嵌套的 if 语句现在什么都不做。理想情况下,我希望能够为 inputValidation 函数调用提供一个额外的参数,如果我要求该字段只接受非数字,我可以将其设置为 true。但是我在下面写的嵌套 if 语句同样有效!
const firstName = document.getElementById('fname');
const lastName = document.getElementById('lname');
const email = document.getElementById('email');
const fAddress = document.getElementById('first-line-address');
const city = document.getElementById('city');
const country = document.getElementById('country');
const postcode = document.getElementById('postcode');
const submitButton = document.getElementById('submit');
function inputValidation(element, greaterThan, lessThan) {
element.addEventListener('input', function(element) {
if (element.target.value.length >= greaterThan && element.target.value.length <= lessThan) {
submitButton.removeAttribute('disabled');
// nested if statements isNaN
if (element === 'firstName' || element === 'lastName' && isNaN(element.target.value)) {
submitButton.setAttribute('disabled', 'true');
}
} else {
submitButton.setAttribute('disabled', 'true');
}
})
}
inputValidation(firstName, 2, 15);
inputValidation(lastName, 4, 20);
inputValidation(email, 7, 40);
inputValidation(fAddress, 10, 40);
inputValidation(city, 3, 40);
inputValidation(postcode, 8, 8);
【问题讨论】:
-
“嵌套的 if 语句现在什么都不做” - 这是一个使用调试器并更具体的好机会。当
if条件执行时,正在使用的变量的确切运行时值是多少?条件的结果是什么?预期的结果是什么?为什么?作为调试的一部分,您甚至可以将该条件的每个组件提取到它们自己的变量中,并观察每个布尔逻辑的具体结果。任何时候代码不符合您的预期,调试以了解更多信息。 -
要添加到@David 的评论,如果您需要帮助调试,您需要在问题中提供这些初始值和预期结果。在这种情况下,如果您 edit 提出问题,您可以向 HTML 提供具有应该触发嵌套 if 但不触发嵌套的值的输入。
标签: javascript forms function validation