我有以下代码被用作输入字段的验证。但是,我也因为检查输入文件类型字段而陷入困境,我不希望这样做。有没有办法让它忽略文件输入字段?
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++) {
//I only want the following condition statement to run if the current element is not a file field.
// 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
}
任何帮助都将不胜感激。
答案 0 :(得分:2)
一种选择是改为使用querySelectorAll
,然后使用:not([type="file"])
:
y = x[currentTab].querySelectorAll('input:not([type="file"])');
除了Javascript外,您还可以考虑将字段required
设置为有助于改善UI的功能。
要稍微重构一下,请考虑使用更有意义的变量名,并使用classList.add
以避免将重复的类属性添加到元素:
function validateForm() {
const thisTab = document.getElementsByClassName("tab")[currentTab];
const inputs = thisTab.querySelectorAll('input:not([type="file"])');
let valid = true;
for (const input of inputs) {
if (input.value === '') {
input.classList.add('invalid');
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
thisTab.classList.add('finish');
}
return valid; // return the valid status
}