【发布时间】:2019-06-03 18:00:02
【问题描述】:
我创建了函数来验证我的表单。但是我希望它们在我单击提交按钮时立即运行。所以,我有一个 formValidate 函数,然后我有一个 firstNameValidate、lastNameValidate 等。
我的问题是,我将如何创建 formValidate 函数来运行我拥有的函数,但只有在所有函数都为真时才提交表单?
function firstNameValidate() {
// Making sure that the firstname input is not blank
if (firstName.value.length == 0) {
// If the firstname input is blank, then return the error text below
error.innerHTML = 'Please Enter a Valid First Name, Cannot be Blank';
// Error text css class
error.className = 'error';
// Making sure that the browser window focuses on the error
firstName.focus();
// Does not let the browser submit the form
// this statement makes sure that the input has only letters
return false;
} else if (!firstName.value.match(letter)) {
// // If the input has something other then numbers, show this error.
error.innerHTML =
'Please Enter a Valid First Name, Cannot contain characters(!@#) or numbers';
// // error text css class
error.className = 'error';
// browser window focuses on error
firstName.focus();
// Form does not submit
return false;
}
if (firstName.value.length > 0 && firstName.value.match(letter)) {
error.className = '';
error.innerHTML = '';
return true;
}
}
我可以获取名字和姓氏来验证,但是如果填写了其中一个,它会发送表单。所以 return true 和 return false 我认为是错误的。
【问题讨论】:
-
这应该是默认情况:你检查每个字段,
return false;如果无效,那么最后你return true;。这意味着,如果您遇到任何验证错误,则始终返回 false,否则返回 true。 -
1.不需要最后一个 if。 2.
document.querySelector("form").onsubmit = function() { return firstNameValidate() && otherValidate() && yetAnotherValidate() }- 也可以查看addEventListener -
所以if语句应该说如果函数返回false,那么返回false,最后它应该有一个return true?这种作品。但是如果用户点击提交按钮并且所有字段都没有填写,那么只会出现第一条错误消息。无论如何都要展示它们?
-
如果您不需要在这些函数中进行非常具体的测试,您可以使用内置验证,例如 = Not empty 或 = 必须是 5 个数字
-
If 语句意味着在某些条件下使用。
if(firstNameValidator() && lastNameValidator() && otherValidator())然后提交您的表单。
标签: javascript forms validation