How can I validate if the user has selected a file to upload?
Edit: bumped
Check it's value property:
In jQuery (since your tag mentions it):
$('#fileInput').val()
Or in vanilla JavaScript:
document.getElementById('myFileInput').value
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;
}
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>
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
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>
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" >
Related
I want to allow the user to upload only pdf files in two input files:
<form onsubmit='return checkExt()' action='upload.php' method='POST'>
<label>upload the first file</label>
<input type='file' name='fileToUpload' id='fileToUpload' required>
<label>upload the secondfile</label>
<input type='file' name='fileToUpload1' id='fileToUpload1' required>
</form>
I used the following script to check the extension of the files-to-upload:
<script>
function checkExt() {
var allowedFiles = [".pdf"];
var form_valid = document.getElementById("fileToUpload");
var form_valid2 = document.getElementById("fileToUpload1");
var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + allowedFiles.join('|') + ")$");
if (!regex.test((form_valid.value.toLowerCase()) &&(form_valid2.value.toLowerCase()))) {
alert('only PDF files are allowed');
return false;
}
return true;
}
</script>
the problem is: when I test it, it only checks on the first file if it is a pdf or not. it does not check on the second file.
You don't need javascript to validate the filetypes. Just use to accept attribute in the input tag.
See documentation here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file
<input name="myFile" type="file" accept=".pdf" multiple>
Your second check in the if condition should mirror the first one and this is the reason why it doesn't work.
Anyway the easiest and scalable way is to iterate over input fields of type "file". Like this:
function checkExt() {
var fileInputs = document.querySelectorAll('input[type="file"]');
var isValid = true;
var allowedFiles = [".pdf"];
var regex = new RegExp(
"([a-zA-Z0-9s_\\.-:])+(" + allowedFiles.join("|") + ")$"
);
fileInputs.forEach(function(input) {
if (!regex.test(input.value.toLowerCase())) {
isValid = false;
}
});
if (isValid) {
alert("only PDF files are allowed");
}
return isValid;
}
This allows you to add as many file input fields as you want.
I'm testing some code I wrote in Google Apps Script. I've required my fields to have text, but when I test it with null fields, the sever side code is run anyway. The code fires the pop-up stating that fields are required, but submits the form when clicking "OK" on the pop-up. I've tested it where I've filled out all the fields and then submitted which uploads perfectly. I think I just have my coding backwards or something in my "onclick". I have a basic knowledge of coding so I'm sorry if this is a dumb question. Thank you, thank you, thank you in advance.
<p>
<form id="myForm">
<h1>NHD Paper Upload</h1>
<label>Name</label>
<input type="text" name="myName" class="required" placeholder="Enter your full name..">
<label>Division</label>
<input type="text" name="myDivision" class="required" placeholder="(ex. Junior or Senior)">
<label>School</label>
<input type="text" name="mySchool" class="required" placeholder="Enter your school..">
<label>Affiliate</label>
<input type="text" name="myAffiliate" class="required" placeholder="Enter your affiliate..">
<label>Select file to upload. Make sure your file is labeled in the following manner <b>LastName_Division_School_State.pdf</b></label>
<input type="file" name="myFile">
<input type="submit" value="Submit File"
onclick="validateForm();
this.value='Please be patient while your paper is uploading..';
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(this.parentNode);
return false;">
<br />
<label><b>Once upload is successful please stay on this window to copy and paste the URL produced on the next screen into registration.</b></label>
<br />
<label><b>If you have any issues or questions please send an email to elaine#nhd.org.</b></label>
</form>
</p>
<div id="output"></div>
<script>
function validateForm() {
var x=document.getElementsByClassName('required');
for(var i = 0; i <x.length; i++){
if (x[i].value == null || x[i].value == "")
{
alert("All fields must be filled out.");
return false;
}
}
}
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
input { display:block; margin: 15px; }
p {margin-left:20px;}
</style>
and here is the javascript
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var dropbox = "NHD Papers";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var blob = form.myFile;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName + ", Division: " + form.myDivision + ", School: " + form.mySchool + ", State: " + form.myState);
return "<h2>File uploaded successfully!</h2><p>Copy and paste the following URL into registration:<br /><br /><strong>" + file.getUrl() + '</strong></p>';
} catch (error) {
return error.toString();
}
}
Right now, google.script.run is being called directly from the submit button.
Current set up:
<input type="submit" value="Submit File"
onclick="validateForm();
this.value='Please be patient while your paper is uploading..';
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(this.parentNode);
return false;">
If you want to prevent google.script.run from being run when a required input field is not filled in, I'd try running the submit event from the <form> tag.
<form id="myForm" onsubmit="validateForm();
this.value='Please be patient while your paper is uploading..';
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(this);
return false;">
Make sure to change this.parentNode to just this, for using this set up.
As a personal preference, I like to put google.script.run it's own function. You are already using a separate function for validateForm(), you could put the google.script.run in that function:
Simplify the form tag to:
<form id="myForm" onsubmit="validateForm()">
Script
function validateForm() {
var x=document.getElementsByClassName('required');
for(var i = 0; i <x.length; i++){
if (x[i].value == null || x[i].value == "")
{
alert("All fields must be filled out.");
return false;
}
this.value='Please be patient while your paper is uploading..';
var myFormObject = document.getElementById('myForm');
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(myFormObject);
}
}
Since the function is outside of the form, you can't use this.parentNode anymore. Get the form by your id. One option is shown in the example code.
I have the form having the follwing fields,
<form onsubmit="return checkcreateform()" action="/gallery/create" method="post" enctype="multipart/form-data">
<label>Type:*</label>
<label for="type-1">
<input type="radio" checked="checked" value="1" id="type-1" name="type">Image
</label>
<br>
<label for="type-2">
<input type="radio" value="2" id="type-2" name="type">Video
</label>
<label class="itemdetailfloatL required" for="file">File:*</label>
<input type="hidden" id="MAX_FILE_SIZE" value="8388608" name="MAX_FILE_SIZE">
<input type="file" tabindex="5" class="text-size text" id="file" name="file">
<input type="submit" value="Create" id="submit" name="submit">
</form>
I want to validate before form submit. Here how can i validate if user select type as Image and upload video or select type as video and upload image ?
We can achieve this by javascript or jquery.Any quick way to validate this ?
Kindly help me on this.
Instead of using onsubmit, use jQuery's submit handler, and validate using some javascript like the following:
function getExtension(filename) {
var parts = filename.split('.');
return parts[parts.length - 1];
}
function isImage(filename) {
var ext = getExtension(filename);
switch (ext.toLowerCase()) {
case 'jpg':
case 'gif':
case 'bmp':
case 'png':
//etc
return true;
}
return false;
}
function isVideo(filename) {
var ext = getExtension(filename);
switch (ext.toLowerCase()) {
case 'm4v':
case 'avi':
case 'mpg':
case 'mp4':
// etc
return true;
}
return false;
}
$(function() {
$('form').submit(function() {
function failValidation(msg) {
alert(msg); // just an alert for now but you can spice this up later
return false;
}
var file = $('#file');
var imageChosen = $('#type-1').is(':checked');
if (imageChosen && !isImage(file.val())) {
return failValidation('Please select a valid image');
} else if (!imageChosen && !isVideo(file.val())) {
return failValidation('Please select a valid video file.');
}
// success at this point
// indicate success with alert for now
alert('Valid file! Here is where you would return true to allow the form to submit normally.');
return false; // prevent form submitting anyway - remove this in your environment
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="/gallery/create" method="post" enctype="multipart/form-data">
<label>Type:*</label>
<label for="type-1">
<input type="radio" checked="checked" value="1" id="type-1" name="type">Image
</label>
<label for="type-2">
<input type="radio" value="2" id="type-2" name="type">Video
</label> <br />
<label class="itemdetailfloatL required" for="file">File:*</label>
<input type="hidden" id="MAX_FILE_SIZE" value="8388608" name="MAX_FILE_SIZE">
<input type="file" tabindex="5" class="text-size text" id="file" name="file">
<br/>
<input type="submit" value="Create" id="submit" name="submit">
</form>
tested in IE8, RockMelt (based on Chrome) and Firefox 7: http://jsfiddle.net/Ngrbj/4/
Every File type has a 'type' property, for example: 'image/jpeg', 'audio/mp3' and so on...
This is an example for one way to check the type of the file by using the 'match' method (of strings):
function getFileType(file) {
if(file.type.match('image.*'))
return 'image';
if(file.type.match('video.*'))
return 'video';
if(file.type.match('audio.*'))
return 'audio';
// etc...
return 'other';
}
You can also write it the boolean way:
function isImage(
return !!file.type.match('image.*');
}
The answer provided works, but something that will run a little faster with a lot fewer lines for the validation code, using javascript array functions:
var extensionLists = {}; //Create an object for all extension lists
extensionLists.video = ['m4v', 'avi','mpg','mp4', 'webm'];
extensionLists.image = ['jpg', 'gif', 'bmp', 'png'];
// One validation function for all file types
function isValidFileType(fName, fType) {
return extensionLists[fType].indexOf(fName.split('.').pop()) > -1;
}
Then, the if statement in the submit code is just swapped with:
if (imageChosen && !isValidFileType(file.val(), 'image')) {
return failValidation('Please select a valid image');
}
else if (!imageChosen && !isValidFileType(file.val(), 'video')) {
return failValidation('Please select a valid video file.');
}
Using files property on input:file you can loop through file objects and check type property
$('#upload').on("change", function(){
var sel_files = document.getElementById('upload').files;
var len = sel_files.length;
for (var i = 0; i < len; i++) {
var file = sel_files[i];
if (!(file.type==='application/pdf')) {
continue;
}
}
});
<div class="modal">
<form id="form-upload">
<input type="file" name="upload" id="upload" multiple>
<br/>
</form>
</div>
As already said, a file has a type property.
You could compare the file type to a list of supported types like this:
const validFileTypes = ['image/jpeg', 'image/jpg', 'image/png'];
const fileTypeValid = (file, fileTypes) => {
return fileTypes.some((fileType) => fileType === file.type);
}
// ... call fileTypeValid with the two parameters
you can try this:
function getFile(fieldId) {
var fileInsert = document.getElementById(fieldId).value;
fileName = fileName.split('/');
fileName = fileName[fileName.length];
extentions = fileName.split('.');
extentions = extentions[extentions.length];
return extentions;
}
You can use this function in your checkcreateform()
First you should change your html like this:
<input type="file" tabindex="5" class="text-size text" id="file" name="file" onchange="checkeExtension(this.value,"submit");">
Then, you need a function like this:
///image 1 and video 2
//you can extend file types
var types= {
'jpg' :"1",
'avi' :"2",
'png' :"1",
"mov" : "2",
}
function checkeExtension(filename,submitId) {
var re = /\..+$/;
var ext = filename.match(re);
var type = $("input[type='radio']:checked").val();
var submitEl = document.getElementById(submitId);
if (types[ext] == type) {
submitEl.disabled = false;
return true;
} else {
alert("Invalid file type, please select another file");
submitEl.disabled = true;
return false;
}
}
Internet Explorer, the bane of my development life, refusing again to do what other browsers seem to do effortlessly. I am trying to clear the browse code/value if the user selects a file type that isn't allowed. Works in FF but not IE 9. Thanks
<script type="text/javascript">
<!--
extArray = new Array(".jpg", ".png");
function LimitAttach(form, file) {
allowSubmit = false;
if (!file) return;
while (file.indexOf("\\") != -1)
file = file.slice(file.indexOf("\\") + 1);
ext = file.slice(file.indexOf(".")).toLowerCase();
for (var i = 0; i < extArray.length; i++) {
if (extArray[i] == ext) {
allowSubmit = true;
break;
}
}
if (allowSubmit) {
return true;
} else {
alert("Please only upload files that end in types: "
+ (extArray.join(" ")) + "\nPlease select a new "
+ "file to upload and submit again.");
document.getElementById('photobrowser').value = "";
return false;
}
}
-->
</script>
<form action="process.php" method="POST" enctype="multipart/form-data" name="formUpload">
<label>Picture:</label>
<input type="file" name="photo" id="photobrowser" onchange="return LimitAttach(formUpload, formUpload.photo.value)" tabindex="4">
<input type="hidden" name="subphoto" value="<?php echo $newCount ?>" />
<input type="image" src="styling/images/button-add-photo.png" id="subBtn" tabindex="6" />
</form
Browsers differ greatly on their restrictions with file inputs. File inputs allow the user to interact with and select files within their file system. So all browsers restrict JS from selecting files automatically. IE goes further to disallow changing the input select at all, even to a blank string. This actually makes sense since, if you are not allowing the selection of a given file, why should you be allowed to change it at all?
And, rather than validating it in JS you should be validating the files on the backend. Frontend validation is okay for ease of use, but even when it is in place there should always be backend validation. Users can simply turn off JS, use something like firebug to alter it or even (sometimes) download the file to their local machine, change it, then use it to submit to your site.
Have you tried passing this into the JS method, instead of finding it by the ID?:
onchange="return LimitAttach(this, this.value);"
JavaScript:
function LimitAttach(input, file) {
allowSubmit = false;
if (!file) return;
while (file.indexOf("\\") != -1)
file = file.slice(file.indexOf("\\") + 1);
ext = file.slice(file.indexOf(".")).toLowerCase();
for (var i = 0; i < extArray.length; i++) {
if (extArray[i] == ext) {
allowSubmit = true;
break;
}
}
if (allowSubmit) {
return true;
} else {
alert("Please only upload files that end in types: "
+ (extArray.join(" ")) + "\nPlease select a new "
+ "file to upload and submit again.");
input.value = "";
return false;
}
}
EDIT
This is kind of a hack, but you might want to give it a shot:
function checkImg(val){
var dgr = val.value;
dgr = dgr.substr(dgr.length-4, dgr.length)
dgr = dgr.toLowerCase();
if (dgr =='.jpg' || dgr == 'jpeg' || dgr== '.gif'){
alert('image');
}else{
alert('not image');
var objD = document.forms['form1'].divR;
objD.innerHTML = '';
objD.innerHTML = '<input id="uImg" name="uImg" type="file" class="defText" style="font-size: 10pt" onchange="javascript: checkImg(this);" size="30">';
}
}
<form name="form1" id="form1" method="post">
<div id="divR" name="divR">
<input id="uImg" name="uImg" type="file" class="defText" style="font-size: 10pt" onchange="javascript: checkImg(this);" size="30">
</div>
</form>
i have a form like this:
<form method=post src=upload enctype="multipart/form-data">
<input name="img1" id="img1" type="file">
<input type="submit" value="Upload">
</form >
Please how can I valid this form using javascript so that only jpg files are uploaded. thanks for reading.
You can bind the onsubmit event of your form, and check if the value of your file input ends with ".jpg" or ".jpeg", something like this:
window.onload = function () {
var form = document.getElementById('uploadForm'),
imageInput = document.getElementById('img1');
form.onsubmit = function () {
var isValid = /\.jpe?g$/i.test(imageInput.value);
if (!isValid) {
alert('Only jpg files allowed!');
}
return isValid;
};
};
Check the above example here.
Form :-
<form method=post src=upload enctype="multipart/form-data" onsubmit="return validateFile()">
<input name="img1" id="img1" type="file">
<input type="submit" value="Upload">
</form>
Javascript Code:-
function validateFile()
{
var allowedExtension = ['jpeg', 'jpg'];
var fileExtension = document.getElementById('img1').value.split('.').pop().toLowerCase();
var isValidFile = false;
for(var index in allowedExtension) {
if(fileExtension === allowedExtension[index]) {
isValidFile = true;
break;
}
}
if(!isValidFile) {
alert('Allowed Extensions are : *.' + allowedExtension.join(', *.'));
}
return isValidFile;
}
if you want to add more image extensions please add in allowedExtension array;
var allowedExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp'];
Array of the image extensions
let allowedExtension = ['image/jpeg', 'image/jpg', 'image/png','image/gif','image/bmp'];
get the type of image
//----<input type="file" id='userimage' accept="image/*" name='userimage'>-----
let type = document.getElementById('userimage').files[0].type;
check type have included inside the allowed extension array :)
if(allowedExtension.indexOf(type)>-1)
{
alert('ok')
}else{
alert('Not a image')
}
}
This is a simpler and more robust way to validate an image, and you don't have to think about all the possible image extensions out there.
document.body.querySelector('input[type="file"]')
.addEventListener('change', function () {
if (this.files[0] && this.files[0].type.includes('image')) {
console.log('file is an image');
} else {
console.log('file is not an image');
}
});
If you want strictly jpg
document.body.querySelector('input[type="file"]')
.addEventListener('change', function () {
if (this.files[0] && this.files[0].type === 'image/jpeg') {
console.log('file is jpg');
} else {
console.log('file is not jpg');
}
});
You can use the "accept" paramter to the input tag:
<input name="img1" id="img1" type="file" accept="image" />
Its not JavaScript but should still be helpful to prevent the user from even attempting to upload a non-image file.
A Google search unearthed this: http://www.webdeveloper.com/forum/archive/index.php/t-104406.html
For your application, I would recommend running the input through:
function valid(a){
return a.indexOf(".jpg") != -1 && a.type == file;
}
That should work.
71944 has some javascript that looks like it might do what you need. Bear in mind that it's only client side validation, so you'll still want to validate it on the server too.
<script>
var fileInput = document.getElementById("fileInput");
fileInput.addEventListener("change",function(event){
document.getElementById("name").innerHTML = "NAME: " + event.target.files[0].name;
document.getElementById("type").innerHTML = "TYPE: " + event.target.files[0].type;
document.getElementById("size").innerHTML = "SIZE: " + event.target.files[0].size;
});
</script>
<input type="file" id="fileInput" name="file"/>