php - Javascript validation not working for checking file which is being uploaded ← (PHP, JavaScript, JQuery)

I am designing a form where a user has to upload a file. I am using javascript for client side validation if case the user has not uploaded a file, due to which the form will not be submitted. It is working for all the other fields in the form but not for the image file being upload. It is entering all the functions except for my image function

Here is an extract of the code:

      <form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST" onsubmit="return 
       validateForm()">


            <h3>Select image:
                <input type="file" name="fImg" id="fImge" accept="image/*">
            </h3>

            <input style="position: relative;top:-20px;left:10px; margin-bottom:5px ; 
           width:150px;height: 30px; float:right;background: #8B0000" type="submit" name="submit" 
           value="Save Changes">
      </form>


    <script>
    function validateForm()
    {


        if(!checkBlankImageById('fImge', 'Please choose an image'))
            return false;

        return true;
    }   //end validateForm()
    </script>

and in my external js file

    function checkBlankImageById(obj_id, obj_label)
    {
     alert('entered');
     if($("#" + obj_id).files.length ==0)
    {

       alert(obj_label);
       return false;
    }
     return true;

}

Answer



Solution:

Source

How to check if input file is empty in jQuery

jQuery

if ($("#"+obj_id).get(0).files.length === 0) {
    console.log("No files selected.");
}

Vanilla Javscript

if( document.getElementById("videoUploadFile").files.length == 0 ){
    console.log("no files selected");
}

Explanation : You are trying vanilla javascript way of getting the length of the files from jQuery Object

Source