0

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.

5 Answers 5

1

You are not doing your checking against the file's name, but against a Fake Path, generally something like "C:\fakepath\file_name.ext".

The File's name is accessible as the .name property of the File object you get:

var input = document.querySelector('input');
input.onchange = function(e) {
  // grab the File object that has been selected by the user
  var file_object = input.files[0];
  // here you have the file's name
  var file_name = file_object.name;

  // now you can do your check
  if ((/^[a-z0-9\s\,\.\-\_]{5,50}\.(?:jpg|jpeg)$/i.test(file_name)) == false) {
    alert("Filename can have only letters (a-z), numbers, spaces, dots, '-' and '_'!");
    input.value = "";
  }
  console.log("for info, the input's value was ", input.value);
  console.log("while the file's name was ", file_name);
};
<input type="file">

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This is the solution :). I've adapted to my needs, but works perfect if access only the filename input.files[0], not the whole path.
0

Your regexp need letters or digits and necessarily 'space', comma, dot, -, _ I think you meant this

   /[a-zA-Z0-9\s\,\.\-\_]{5,50}\.(?:jpg|jpeg)$/i

2 Comments

Not the alert("Filename can have only letters (a-z), numbers, spaces, dots, '-' and '_'!"); is the problem. I'll customize it after will work... The filename must have only a-z letters, 0-9 digits, spaces, commas, dots, hyphens and underlines. (the filename can combine in any order all of them, it is practically the most common filenames; i only wish to block upload for files with all kind of strange characters from Chinese, Vietnamese...)
Yes, i understand you, but your regular expression does not what you want. Symbols \s\,\.\-_ are must unclude in [] for this. Try /^[a-zA-Z0-9\s\,\.\-_]{5,50}\.(?:jpg|jpeg)$/i
0

You've made a small mistake in your regular expression. This bit:

[a-zA-Z0-9]\s\,\.\-\_

Means: any lowercase letter, any uppercase letter or any digit followed by a whitespace character, a comma, a period, a dash and an underscore.

The [] operator indicates a selection. You should move everything inside it.

The A-Z syntax is just shorthand for ABCD...WXYZ.

Change the expression part to:

[a-zA-Z0-9\s\,\.\-\_]

Comments

0

Your regular expression seems to be correct. Your missing to return true in the end of your function after all the conditioning. Try this:

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;
} else {
    // stuf to do if everything is good, rhen return true.
    return true;
}
}

4 Comments

No, your solution is not working. Try it here jsfiddle.net/jacob19/a3fLog6r/5 and maybe you'll find a solution, because in the past 5 hours i struggled only with this problem. :)
No, no errors. But the validation isn't working as it should. You can upload any filename (with all kind of characters !@#$%^&*...). You can test yourself and modify the code as you wish in the jsfiddle.net/jacob19/a3fLog6r/5
@Jacob19 I edited my answer check it out. Removing ^ and $ make it work.
Have you tried to select an image file called for example myimage#.jpg and the validation returned the alert ? I tried and the validation allowed that name, doesn't return the alert message even after i removed ^ $.
0

After the feedback from @Kaiido here's my solution that works and accomplish these tasks:

  1. Check the file size.
  2. Validate the file name.
  3. Validate the file extension.

The JS code is smaller and i test it with various file names and sizes.

const input = document.querySelector('#uploadFile');
input.onchange = function(e) {
if (((input.files[0].size/1024)/1024) > 4) {
	alert("Please optimize your file to maximum 4MB!");
	input.value = "";
}
else if ((/^[a-z0-9\s\,\.\-\_]{5,50}\.(?:jpg|jpeg)$/i.test(input.files[0].name)) == false) {
    //i tested for image file, but i'll use it for various extension,
    //so you can just add other extensions in this part of the regex code (?:jpg|jpeg|pdf|docx)
	alert("Filename between 5-50 characters (letters (a-z), numbers, spaces, dots, '-' and '_').");
	input.value = "";
}
};
<form>
<input type="file" id="uploadFile">
</form>

PS: Never forget that this validation is in frontend (client side), so you must have a validation rule for backend too. :)

Cheers!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.