Inputing file via the button works, but I want it to make sure the criterias for the file submiting are respected, How do I apply them so that the file meet the criterias and the error message is shown ?
Here's my code :
<form action="#" class="form-horizontal">
Upload File.
<input type="file" id="fileinput" name="fileinp" class="form-control" multiple>
<br>
<p id="ptagmsg"></p>
<input type="submit" name="bxt" id="submitbutton" class="btn-primary" value="send">
</form>
document.addEventListener('DOMContentLoaded', function(){
let inpFile = document.querySelector('#fileinput');
var pTagMsg = document.querySelector('#ptagmsg');
let kB = 1024;
let mB = 1024 * 1024;
let submitButton = document.querySelector('#submitbutton');
submitButton.addEventListener('click', function(){
var objFileList = inpFile.files;
var fileObj = inpFile.files[0];
let fileValue = inpFile.value;
var fileName = fileObj.name;
var fileSize = Math.round(fileObj.size / kB); // to kB OR mB
var fileExt = fileObj.name.slice(-4);
if(objFileList.length !== 0){
// file is selected from file explorer.
if(fileValue.length != 0){
// check size and extenstion, file must be .pdf and greater than 200 kb.
if((fileExt != '.pdf') || (fileSize <= 200) ){
pTagMsg.innerHTML = ' fileErrorMsg: file size must be 200KB and extension of .pdf';
pTagMsg.style.backgroundColor = 'red';
event.preventDefault();
} else {
// if file criteria is satisfied.
pTagMsg.style.backgroundColor = 'green';
pTagMsg.innerHTML = ' File OK';
event.preventDefault();
}
}
} else if(objFileList.length === 0){
pTagMsg.innerHTML = 'please select a file.';
event.preventDefault();
}
});
});