How to validate a file upload field using Javascript/jquery

前端 未结 6 960
伪装坚强ぢ
伪装坚强ぢ 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: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:

    
    
    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;
    }
    

提交回复
热议问题