How to validate a file upload field using Javascript/jquery

前端 未结 6 925
伪装坚强ぢ
伪装坚强ぢ 2021-02-07 03:54

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

Edit: bumped

相关标签:
6条回答
  • 2021-02-07 04:16

    Check it's value property:

    In jQuery (since your tag mentions it):

    $('#fileInput').val()
    

    Or in vanilla JavaScript:

    document.getElementById('myFileInput').value
    
    0 讨论(0)
  • 2021-02-07 04:18

    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>
    
    0 讨论(0)
  • 2021-02-07 04:20

    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
    
    0 讨论(0)
  • 2021-02-07 04:27

    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>
    
    0 讨论(0)
  • 2021-02-07 04:27

    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" >

    0 讨论(0)
  • 2021-02-07 04:30

    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;
    }
    
    0 讨论(0)
提交回复
热议问题