Javascript not clearing box in IE - javascript

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>

Related

check file extensions for more than one upload box

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.

HTML <input> Required Attribute Fails to Prevent Form from Submitting in Apps Script App

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.

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