如何在验证脚本中排除必填字段?



我试图创建一个多步骤表单,基于所需字段的验证。目前我使用的Javascript只是寻找填充的字段来验证表单。但是,如何使它忽略未标记为"必需"的字段?在html?

谢谢!

function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false:
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}

但是我如何使它忽略未标记为"必需"的字段?在html?

下面的解决方案检查input元素中的required属性。所以在for循环中,你首先要做的是if(!y[i].required){ continue; },换句话说,如果y[i].requiredundefined,那么continue(或者跳过这个迭代)。

function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// --> if y[i].required is undefined... skip to the next <--
if(!y[i].required){ continue; }
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false:
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}