How To Validate A File Upload Field Using Javascript/jquery
How can I validate if the user has selected a file to upload? Edit: bumped
Solution 1:
Check it's value
property:
In jQuery (since your tag mentions it):
$('#fileInput').val()
Or in vanilla JavaScript:
document.getElementById('myFileInput').value
Solution 2:
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; }
Solution 3:
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;
functionvalidate_fileupload(input_element)
{
var el = document.getElementById("feedback");
var fileName = input_element.value;
var allowed_extensions = newArray("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;
}
functionvalid_form()
{
return valid;
}
</script><divid="feedback"style="color: red;"></div><formmethod="post"action="/image"enctype="multipart/form-data"><inputtype="file"name="fileName"accept=".jpg,.png,.bmp"onchange="validate_fileupload(this);"/><inputid="uploadsubmit"type="submit"value="UPLOAD IMAGE"onclick="return valid_form();"/></form>
Solution 4:
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
Solution 5:
I got this from some forum. I hope it will be useful for you.
<scripttype="text/javascript">functionvalidateFileExtension(fld) {
if(!/(\.bmp|\.gif|\.jpg|\.jpeg)$/i.test(fld.value)) {
alert("Invalid image file type.");
fld.form.reset();
fld.focus();
returnfalse;
}
returntrue;
} </script></head><body><form...etc...onsubmit="return
validateFileExtension(this.fileField)"><p><inputtype="file"name="fileField"onchange="return validateFileExtension(this)"><inputtype="submit"value="Submit"></p></form></body>
Post a Comment for "How To Validate A File Upload Field Using Javascript/jquery"