24

How can I validate if the user has selected a file to upload?

Edit: bumped

0

7 Answers 7

27

Check it's value property:

In jQuery (since your tag mentions it):

$('#fileInput').val()

Or in vanilla JavaScript:

document.getElementById('myFileInput').value
Sign up to request clarification or add additional context in comments.

Comments

21

My function will check if the user has selected the file or not and you can also check whether you want to allow that file extension or not.

Try this:

<input type="file" name="fileUpload" onchange="validate_fileupload(this.value);">

function validate_fileupload(fileName)
{
    var allowed_extensions = new Array("jpg","png","gif");
    var file_extension = fileName.split('.').pop().toLowerCase(); // split function will split the filename by dot(.), and pop function will pop the last element from the array which will give you the extension as well. If there will be no extension then it will return the filename.

    for(var i = 0; i <= allowed_extensions.length; i++)
    {
        if(allowed_extensions[i]==file_extension)
        {
            return true; // valid file extension
        }
    }

    return false;
}

2 Comments

The for loop should be i < allowed_extensions.length; NOT <= as this will yeild four iterations of the loop in the above example, and thus passign an undefined filename to the function will return TRUE.
Just to mention. that by checking for the extension you are allowing people to upload .exe's by faking the extension.
2

Building on Ravinders solution, this code stops the form being submitted. It might be wise to check the extension at the server-side too. So you don't get hackers uploading anything they want.

<script>
var valid = false;

function validate_fileupload(input_element)
{
    var el = document.getElementById("feedback");
    var fileName = input_element.value;
    var allowed_extensions = new Array("jpg","png","gif");
    var file_extension = fileName.split('.').pop(); 
    for(var i = 0; i < allowed_extensions.length; i++)
    {
        if(allowed_extensions[i]==file_extension)
        {
            valid = true; // valid file extension
            el.innerHTML = "";
            return;
        }
    }
    el.innerHTML="Invalid file";
    valid = false;
}

function valid_form()
{
    return valid;
}
</script>

<div id="feedback" style="color: red;"></div>
<form method="post" action="/image" enctype="multipart/form-data">
  <input type="file" name="fileName" accept=".jpg,.png,.bmp" onchange="validate_fileupload(this);"/>
  <input id="uploadsubmit" type="submit" value="UPLOAD IMAGE" onclick="return valid_form();"/>
</form>

Comments

1

In Firefox at least, the DOM inspector is telling me that the File input elements have a property called files. You should be able to check its length.

document.getElementById('myFileInput').files.length

1 Comment

1

I got this from some forum. I hope it will be useful for you.

<script type="text/javascript">
 function validateFileExtension(fld) {
    if(!/(\.bmp|\.gif|\.jpg|\.jpeg)$/i.test(fld.value)) {
        alert("Invalid image file type.");      
        fld.form.reset();
        fld.focus();        
        return false;   
    }   
    return true; 
 } </script> </head>
 <body> <form ...etc...  onsubmit="return
 validateFileExtension(this.fileField)"> <p> <input type="file"
 name="fileField"  onchange="return validateFileExtension(this)">
 <input type="submit" value="Submit"> </p> </form> </body>

1 Comment

Welcome to SO. If you get code from another source you should properly attribute it, and/or link to it as this could be violation of copyright, and it's at least courtesy to give credit where it is due.
0

Simple and powerful way(dynamic validation)

place formats in array like "image/*"

var upload=document.getElementById("upload");
var array=["video/mp4","image/png"];
upload.accept=array;
upload.addEventListener("change",()=>{

console.log(upload.value)
})
<input type="file" id="upload" >

Comments

0

The Best way to validate Input , and then if not valid empty input So, No need to again validate in Form Submit ... function validate_fileupload(obj) { var fileName=obj.value; var allowed_extensions = new Array("pdf"); var file_extension = fileName.split('.').pop().toLowerCase(); // split function will split the filename by dot(.), and pop function will pop the last element from the array which will give you the extension as well. If there will be no extension then it will return the filename.

    for(var i = 0; i <= allowed_extensions.length; i++)
    {
        if(allowed_extensions[i]==file_extension)
        {
            return true; // valid file extension
        }
    }
    Swal.fire({
        title: "error",
        text: 'PDF ONLY',
        icon: "error"
    });
    obj.value='';
    return false;
}


<input onchange="validate_fileupload(this);" type="file" class="form-control" name="referral_file"
                                    id="pharmacy_referral_file">

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.