Javascript 多个空字段的验证
我正在尝试验证表单中的两个字段。 但它只显示一个字段的错误消息。 以下是Javascript代码:Javascript 多个空字段的验证,javascript,validation,Javascript,Validation,我正在尝试验证表单中的两个字段。 但它只显示一个字段的错误消息。 以下是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";
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>
\
如“Disha”所述,如果您需要测试所有错误,则不能在每个If块中放置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;
这应该可以按照您的意愿工作。试试这段代码
- JavaScript `
将
return
语句放在每个if
语句的末尾,而不是后面
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;
}`