HTML
<form>
<input type="file" onchange="return validateSize()" id="uploadFile" accept="image/*">
<button type="submit">Send</button>
</form>
JavaScript
function validateSize() {
const file = document.querySelector('#uploadFile');
const file_name = file.value;
const extension = file_name.split('.').pop().toLowerCase();
const size = file.files[0].size;
const allowedFormats = ["jpg", "jpeg"];
if (((size/1024)/1024) > 4) {
// works perfect
alert("Please optimize your image to maximum 4MB!");
file.value = "";
return false;
}
else if (!(allowedFormats.indexOf(extension) > -1)) {
// works perfect
alert("Please save your image in JPG format!");
file.value = "";
return false;
}
else if ((/^[a-z0-9\s\,\.\-\_]{5,50}\.(?:jpg|jpeg)$/i.test(file_name)) == false) {
// this IS NOT working
alert("Filename can have only letters (a-z), numbers, spaces, dots, '-' and '_'!");
file.value = "";
return false;
}
}
The size validation WORKS.
The extension validation WORKS.
The filename validation NOT work.
I wish to have this regex condition:
/^[a-z0-9\s\,\.\-\_]{5,50}\.(?:jpg|jpeg)$/i
And if the filename have other characters that aren't included in the regex to return the alert.
Thanks!
PS: You can test the code here https://jsfiddle.net/jacob19/a3fLog6r/5/ and see if you'll find a solution.