need some help with file upload validation, currently i have a script that checks for a max upload size and for proper file type.
The validation works fine however the "file type" validation part comes up with the error message if there is no file chosen either.
Is there a way to modify to code to say if there is no file chosen submit the form and if there is a file check if its the correct type before submitting.
Thanks, let me know if you need more info.
<form method="post" enctype="multipart/form-data" action="thankyou.html" name="SampleForm" id="app-form">
<p>
<label class="sr-only" for="upload">Attach Resume </label>
<input type="file" name="fileUpload" class="upload-file" data-max-size="5242880" id="fileUpload" accept=".pdf,.jpg,.jpeg,.png,.doc,.docx">
<br>(.pdf, .jpg, .png, .doc, .docx file types only) Max 5MB
<span class="error error-msg"></span>
<span class="error error-msg-two"></span>
</p>
<p>
<input type="submit" id="submitbutton" value="Submit" name="submitbutton">
</p>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
//attachments
//for file size
var fileInput = $('.upload-file');
var maxSize = fileInput.data('max-size');
var errmsg = 'File size is larger than 5MB';
$('#app-form').submit(function(e){
if(fileInput.get(0).files.length){
var fileSize = fileInput.get(0).files[0].size; // in bytes
if(fileSize>maxSize){
$('.error-msg').text(errmsg);
return false;
}else{
''
}
}
});
//for file types
$('#app-form').submit(function(e){
var allowedFiles = [".doc", ".docx", ".pdf",".jpg",".jpeg",".png"];
var fileUpload = $("#fileUpload");
var errmsgtwo = 'Please upload the correct file type';
var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + allowedFiles.join('|') + ")$");
if (!regex.test(fileUpload.val().toLowerCase())) {
$('.error-msg-two').text(errmsgtwo);
$('.error-msg').text('');
return false;
}else{
$('.error-msg-two').text('');
return true;
}
});
});
</script>