如果此功能分为三个单独的功能(一个用于照片,两个用于照片,一个用于视频上传,三个功能),则我有代码可以成功检测文件类型(在用户上传时)。在我的<input/>
标签上,每个相应的输入都有onchange="fileValidation()"
。我试图将其合并为一个功能,以便在将其分为三个功能时可以执行上述成功的功能。
我正在使用香草JS。一切都在一个页面上。我的猜测是,如果三个单独的输入标签具有相同的fileValidation()
函数,它将无法正常工作。换句话说-如果有人想上传视频,那么其他两个<input/>
标签可能会引起混淆...但是我可能错了吗?
如何将所有这些if()
合并到一个函数中,这样我才能像分离为三个函数那样重新工作?以下代码供参考。
function fileValidation() {
const realFileBtn = document.getElementById("real-file");
const realFileW9 = document.getElementById("real-file-w9");
const realFileVideo = document.getElementById("real-file-video");
let filePathWinnerPhoto = realFileBtn.value;
let filePathW9 = realFileW9.value;
let filePathVideo = realFileVideo.value;
// Allowing file type
let allowedExtensionsWinnerPhoto = /(\.jpg|\.png|\.HEIC|\.JPEG|\.pdf)$/i;
let allowedExtensionsW9 = /(\.jpg|\.png|\.HEIC|\.JPEG|\.pdf)$/i;
let allowedExtensionsVideo = /(\.mp4|\.mov)$/i;
if (!allowedExtensionsWinnerPhoto.exec(filePathWinnerPhoto)) {
alert('Invalid file type');
realFileBtn.value = '';
return false;
} else {
console.log("file accepted");
fileAcceptedFlag = true;
}
if (!allowedExtensionsW9.exec(filePathW9)) {
alert('Invalid file type');
realFileW9.value = '';
return false;
} else {
console.log("file accepted");
fileAcceptedW9Flag = true;
}
if (!allowedExtensionsVideo.exec(filePathVideo)) {
alert('Invalid file type');
realFileVideo.value = '';
return false;
} else {
console.log("file accepted");
fileAcceptedVideoFlag = true;
}
return fileAcceptedFlag || fileAcceptedW9Flag || fileAcceptedVideoFlag;
答案 0 :(得分:0)
以下更新包括一个error变量,用于保存错误,并在末尾仅返回一次,并在存在错误时发出警报。为了进行测试,我输入了文件名的值,并注释掉了输入值的重置。
# Variable tests
#
#
[myvars]
var_a='home'
var_b='car'
var_c=15.5
var_d=[2.1 3.4 4.6]
var_e=[[ 1.1 2.2 2.233]
[ 1.00000000e+02 1.17809494e+03 4.9410e+02]
[ 2.00000000e+04 1.20e+01 1.2323e+04]]