这是更长(25个或更多)函数的一部分,但它使您对正在发生的事情有所了解。似乎很直接,从第一个字段开始,对其进行验证,如果失败,则弹出警报,然后将光标放在该字段中。
[不幸的是,它正在跳过前十几个字段,并从DateDue字段开始,然后从那里倒退。它也不会弹出警报消息。
该代码在JSHeader中,并通过“提交”按钮调用。
对我在做什么错有任何想法吗?
function validate(){
var validatemsg;
var validateflag;
validateflag = 'false';
if(document.forms[0].LocationName.value == ''){
validatemsg='LOCATION NAME FIELD ERROR: Location Name is required to successfully process your request.';
validateflag='true';
document.forms[0].LocationName.focus()
}
if(document.forms[0].LocPhone.value == '') {
validatemsg='LOCATION PHONE FIELD ERROR: Location Phone is required to successfully process your request.';
validateflag='true';
document.forms[0].LocPhone.focus()
}
if(document.forms[0].LocFax.value == '') {
validatemsg='LOCATION FAX FIELD ERROR: Location Fax is required to successfully process your request.';
validateflag='true';
document.forms[0].LocFax.focus()
}
然后再以完全相同的方式设置另外十几个字段
if(document.forms[0].DateDue.value == '') {
validatemsg='DATE DUE FIELD ERROR: Date Due is required to successfully process your request.';
validateflag='true';
document.forms[0].DateDue.focus()
}
if(document.forms[0].DateDue.value.length != 10) {
validatemsg='DATE DUE FIELD ERROR: Date Due should be in mm/dd/yyyy format.';
validateflag='true';
document.forms[0].DateDue.focus()
}
if(document.forms[0].AgreeType.value == '') {
validatemsg='AGREEMENT TYPE FIELD ERROR: AgreementType is required to successfully process your request.';
validateflag='true';
document.forms[0].AgreeType.focus()
}
if(validateflag == 'true'){
alert(validatemsg);
}
if(validateflag == 'false'){
document.forms[0].submit()
}
}
您需要稍微分开一些东西。当您想在第一次验证失败时停止时,必须退出validate()
函数。
下面看一下(我已添加评论),将return
添加到您的每个if检查中
// Declare these outside the function
var validatemsg;
var validateflag = false; /* don't use a string */
function validate(){
if (document.forms[0].LocationName.value == ''){
validatemsg = 'LOCATION NAME FIELD ERROR: Location Name is required to successfully process your request.';
validateflag = true;
document.forms[0].LocationName.focus();
return; /* <-- Important, get out of the validator */
}
/* add rest of if blocks from here down */
}
if (validateflag){
alert(validatemsg);
}
if (!validateflag){
document.forms[0].submit()
}