2014-10-11 73 views
0

我想验证我的表单中的两个字段。 但它只显示一个字段的错误信息。 以下是Javascript代码:验证多个空字段

function req() { 

    if (document.reg_indi_form.txt_fnm.value=="") { 

     document.getElementById('i').innerHTML="*This field is required"; 
     document.getElementById('i').style.color="red"; 
     return false; 
    } 
    if (document.reg_indi_form.txt_lnm.value=="") { 

     document.getElementById('i1').innerHTML="*This field is required"; 
     document.getElementById('i1').style.color="red"; 
     return false; 
    } 
} 

HTML代码:

<input name="txt_fnm" type="text" id="txt_fnm"/> <label id="i"></label> 
<input name="txt_lnm" type="text" id="txt_lnm"/>\<label id="i1"></label> 
+1

把你的'return'声明在结尾,而不是Ø f在每个if语句之后 – bruchowski 2014-10-11 08:40:28

回答

0

如果你需要得到测试的所有错误,“笛莎”评论说,你不能把一个return语句中的每个如果块。

var noError = true; 

if (document.reg_indi_form.txt_fnm.value=="") { 

    document.getElementById('i').innerHTML="*This field is required"; 
    document.getElementById('i').style.color="red"; 
    noError = false; 
} 
if (document.reg_indi_form.txt_lnm.value=="") { 

    document.getElementById('i1').innerHTML="*This field is required"; 
    document.getElementById('i1').style.color="red"; 
    noError = false; 
} 

return noError; 

这应该像你想要的那样工作。

0

试试这个代码

  • 的JavaScript

    `

功能的validate(){

var isValid = true; 
    if (document.reg_indi_form.txt_fnm.value=="") { 

    document.getElementById('i').innerHTML="*This field is required"; 
    document.getElementById('i').style.color="red"; 
    isValid = false; 
} 
if (document.reg_indi_form.txt_lnm.value=="") { 

    document.getElementById('i1').innerHTML="*This field is required"; 
    document.getElementById('i1').style.color="red"; 
    isValid = false; 
} 
return isValid; 
}`