[英]How to Validate a Form using the Functions I created
我创建了一些函数来验证表单。 但是当我单击提交按钮时,我希望它们全部一次运行。 因此,我有一个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;
}
}
我可以得到名字和姓氏进行验证,但是如果填写了其中的一个,它将发送表格。 因此,我认为返回true和false都是错误的。
function firstNameValidate() {
if (firstName.value.length == 0) {
error.innerHTML = 'Please Enter a Valid First Name, Cannot be Blank';
error.className = 'error';
firstName.focus();
return false;
}
if (!firstName.value.match(letter)) {
error.innerHTML = 'Please Enter a Valid First Name, Cannot contain characters(!@#) or numbers';
error.className = 'error';
firstName.focus();
return false;
} else {
//intended code goes here , or simply return true.
}
}
如果您要进行严格检查,请在if语句中编写所有验证,如果所有内容都正确填充,则在else语句中执行正确的代码,
并在onsubmit表单上调用上述函数,或单击一个按钮即可完成工作。
希望这可以帮助 ..!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.