JS验证-多个循环

时间:2019-03-20 14:20:26

标签: javascript validation

以下验证返回错误“ missing; before statement”。我要验证的表单上有多个字段。一个字段驱动需要验证哪些字段。此字段是包含1到6的单选按钮。如果选择6,则(在我的代码中)tdchars将为123456,如果选择5,则tdchars将为12345,依此类推。变量i将用于将每个数字附加在字段名称的末尾,以引用要验证的正确字段。

我不确定我是否正确创建了for循环。如果我退出循环,可以节省罚款。我将不胜感激。

谢谢。

`function getRadioButtonValue(checkboxname) {  
	var x = checkboxname.length; 
	for (var i=0; i < x; i++) {  
		if (checkboxname[i].checked == true) {  
			return checkboxname[i].value; 
		} 
	} 
	return ""; 
}

//THE CODE BELOW IS USED FOR VALIDATION BEFORE SUBMITTING
function validate() {
errMSG = ""
var f = document.forms[0];
var td = getRadioButtonValue(document.forms[0].RAField);

for (td = 1; td <= 6; td++) {
	If (td = 6) {
	var tdChars ="123456";
	}else if (td = 5) {
	var tdChars = "12345";
	}else if (td = 4) {
	var tdChars = "1234";
	}else if (td = 3) {
	var tdChars = "123";
	}else if (td = 2) {
	var tdChars = "12";
	}else {
	var tdChars = "1";
}
	for (i=0; i <=  tdChars.length; i++) {

if(f.JobGuaranteeDuration.selectedIndex<1){
if (errMSG!="") {
			errMSG += "Select a Guarantee Duration for Roof Contruction(i)\n";
		}else {
			errMSG+="Please correct the following:\n\nSelect a Guarantee Duration for Roof Contruction(i)\n";
		}
	}	
if(f.JobName.value == '') {
if (errMSG!="") {
			errMSG += "Enter the Project Name for Roof Contruction(i)\n";
		}else {
			errMSG+="Please correct the following:\n\nEnter the Project Name for Roof Contruction(i)\n";
		}
	}	
if(f.JobSiteAddress.value =='') {
if (errMSG!="") {
			errMSG += "Enter the Job Site Address for Roof Contruction(i)\n";
		}else {
			errMSG+="Please correct the following:\n\nEnter the Job Site Address for Roof Contruction(i)\n";
		}
	}	
if(f.JobSiteCity.value =='') {
if (errMSG!="") {
			errMSG += "Enter the Job Site City for Roof Contruction(i)\n";
		}else {
			errMSG+="Please correct the following:\n\nEnter the Job Site City for Roof Contruction(i)\n";
		}
	}	
if(f.JobSiteState.value == '') {
if (errMSG!="") {
			errMSG += "Enter the Job Site State for Roof Contruction(i)\n";
		}else {
			errMSG+="Please correct the following:\n\nEnter the Job Site State for Roof Contruction(i)\n";
		}
	}	
if(f.JobSiteZip.value =='') {
if (errMSG!="") {
			errMSG += "Enter the Job Site Zip for Roof Contruction(i)\n";
		}else {
			errMSG+="Please correct the following:\n\nEnter the Job Site Zip for Roof Contruction(i)\n";
		}
	}	
if (errMSG != "") {
alert(errMSG);
f.SaveOptions.value = '0';
return false
}
f.SaveOptions.value = '1';
return true
}
}`

2 个答案:

答案 0 :(得分:0)

我认为您在errMSG = ""函数开头的语句validate()之后缺少分号。

有关背景,另请参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement

答案 1 :(得分:0)

如先前的回答所述,第一个if引起了错误。

也就是说,这里有一个更简单的for循环来获取所需的相同字符串:

tdChars = ""
for(i = 1; i< td + 1; i++){
tdChars = tdChars + i.toString()
}