check file extensions for more than one upload box - javascript

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.

Related

Check file type when form submit?

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

Javascript not clearing box in IE

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>

Validate image type using javascript

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

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

How to have jQuery restrict file types on upload?

I would like to have jQuery limit a file upload field to only jpg/jpeg, png, and gif. I am doing backend checking with PHP already. I am running my submit button through a JavaScript function already so I really just need to know how to check for the file types before submit or alert.
You can get the value of a file field just the same as any other field. You can't alter it, however.
So to superficially check if a file has the right extension, you could do something like this:
var ext = $('#my_file_field').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
alert('invalid extension!');
}
No plugin necessary for just this task. Cobbled this together from a couple other scripts:
$('INPUT[type="file"]').change(function () {
var ext = this.value.match(/\.(.+)$/)[1];
switch (ext) {
case 'jpg':
case 'jpeg':
case 'png':
case 'gif':
$('#uploadButton').attr('disabled', false);
break;
default:
alert('This is not an allowed file type.');
this.value = '';
}
});
The trick here is to set the upload button to disabled unless and until a valid file type is selected.
You could use the validation plugin for jQuery:
http://docs.jquery.com/Plugins/Validation
It happens to have an accept() rule that does exactly what you need:
http://docs.jquery.com/Plugins/Validation/Methods/accept#extension
Note that controlling file extension is not bullet proof since it is in no way related to the mimetype of the file. So you could have a .png that's a word document and a .doc that's a perfectly valid png image. So don't forget to make more controls server-side ;)
For the front-end it is pretty convenient to put 'accept' attribute if you are using a file field.
Example:
<input id="file" type="file" name="file" size="30"
accept="image/jpg,image/png,image/jpeg,image/gif"
/>
A couple of important notes:
The accept attribute is supported in Internet Explorer 10, Firefox, Opera, Chrome, and Safari 6.
It will show text for file extension differently in the file browser dialog from different browsers.
Don't want to check rather on MIME than on whatever extention the user is lying?
If so then it's less than one line:
<input type="file" id="userfile" accept="image/*|video/*" required />
for my case i used the following codes :
if (!(/\.(gif|jpg|jpeg|tiff|png)$/i).test(fileName)) {
alert('You must select an image file only');
}
I try to write working code example, I test it and everything works.
Hare is code:
HTML:
<input type="file" class="attachment_input" name="file" onchange="checkFileSize(this, #Model.MaxSize.ToString(),#Html.Raw(Json.Encode(Model.FileExtensionsList)))" />
Javascript:
//function for check attachment size and extention match
function checkFileSize(element, maxSize, extentionsArray) {
var val = $(element).val(); //get file value
var ext = val.substring(val.lastIndexOf('.') + 1).toLowerCase(); // get file extention
if ($.inArray(ext, extentionsArray) == -1) {
alert('false extension!');
}
var fileSize = ($(element)[0].files[0].size / 1024 / 1024); //size in MB
if (fileSize > maxSize) {
alert("Large file");// if Maxsize from Model > real file size alert this
}
}
If you're dealing with multiple (html 5) file uploads, I took the top suggested comment and modified it a little:
var files = $('#file1')[0].files;
var len = $('#file1').get(0).files.length;
for (var i = 0; i < len; i++) {
f = files[i];
var ext = f.name.split('.').pop().toLowerCase();
if ($.inArray(ext, ['gif', 'png', 'jpg', 'jpeg']) == -1) {
alert('invalid extension!');
}
}
This code works fine, but the only issue is if the file format is other than specified options, it shows an alert message but it displays the file name while it should be neglecting it.
$('#ff2').change(
function () {
var fileExtension = ['jpeg', 'jpg', 'pdf'];
if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
alert("Only '.jpeg','.jpg','.pdf' formats are allowed.");
return false; }
});
This example allows to upload PNG image only.
HTML
<input type="file" class="form-control" id="FileUpload1" accept="image/png" />
JS
$('#FileUpload1').change(
function () {
var fileExtension = ['png'];
if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
alert("Only '.png' format is allowed.");
this.value = ''; // Clean field
return false;
}
});
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="submit" value="Upload" />
</form>
<script>
$('input[type=file]').change(function(){
var file = this.files[0];
name = file.name;
size = file.size;
type = file.type;
//your validation
});
</script>
$("input[name='btnsubmit']").attr('disabled', true);
$('input[name="filphoto"]').change(function () {
var ext = this.value.match(/\.(.+)$/)[1];
switch (ext)
{
case 'jpg':
case 'jpeg':
case 'png':
case 'bmp':
$("input[name='btnsubmit']").attr('disabled', false);
break;
default:
alert('This is not an allowed file type.');
$("input[name='btnsubmit']").attr('disabled', true);
this.value = '';
function validateFileExtensions(){
var validFileExtensions = ["jpg", "jpeg", "gif", "png"];
var fileErrors = new Array();
$( "input:file").each(function(){
var file = $(this).value;
var ext = file.split('.').pop();
if( $.inArray( ext, validFileExtensions ) == -1) {
fileErrors.push(file);
}
});
if( fileErrors.length > 0 ){
var errorContainer = $("#validation-errors");
for(var i=0; i < fileErrors.length; i++){
errorContainer.append('<label for="title" class="error">* File:'+ file +' do not have a valid format!</label>');
}
return false;
}
return true;
}
Here is a simple code for javascript validation, and after it validates it will clean the input file.
<input type="file" id="image" accept="image/*" onChange="validate(this.value)"/>
function validate(file) {
var ext = file.split(".");
ext = ext[ext.length-1].toLowerCase();
var arrayExtensions = ["jpg" , "jpeg", "png", "bmp", "gif"];
if (arrayExtensions.lastIndexOf(ext) == -1) {
alert("Wrong extension type.");
$("#image").val("");
}
}

Categories