如何将三个功能合并为一个功能以执行相同的功能



我有一个代码,如果这个功能被分为三个单独的功能(一个用于2个用于照片,一个用于视频上传(,它可以成功检测文件类型(在用户上传时(。在我的<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;

下面的更新包括一个errors变量,用于保存错误,并在结束时只返回一次,如果存在错误,则会发出警报。为了测试,我输入了文件名的值,并注释掉了输入值的重置。

function fileValidation() {
const realFileBtn = document.getElementById("real-file");
const realFileW9 = document.getElementById("real-file-w9");
const realFileVideo = document.getElementById("real-file-video");
let filePathWinnerPhoto = "test.jp1g";
let filePathW9 = "test.jpxg";
let filePathVideo = "test.mov";
let imgreg = /(.jpg|.png|.HEIC|.JPEG|.pdf)$/i;
let videoreg = /(.mp4|.mov)$/i;
let errors = [];
if(!imgreg.exec(filePathWinnerPhoto)){
errors.push("Winner Photo is not valid");
//realFileBtn.value = "";
}
if(!imgreg.exec(filePathW9)){
errors.push("W9 Photo is not valid");
//realFileW9.value = "";
}
if(!videoreg.exec(filePathVideo)){
errors.push("Video is not valid");
//realFileVideo.value = "";
}
if(errors.length > 0){
alert(errors.join("n"));
}
return (errors.length == 0);
}
fileValidation();

最新更新