7

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.

miken32
  • 42,008
  • 16
  • 111
  • 154
Selom
  • 729
  • 8
  • 15
  • 21
  • Does this answer your question? [How to check file MIME type with JavaScript before upload?](https://stackoverflow.com/questions/18299806/how-to-check-file-mime-type-with-javascript-before-upload) – miken32 Aug 16 '22 at 18:23

9 Answers9

14

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.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • You're welcome Selom, remember also to write validation code on the server-side, a user with JavaScript disabled will be able to upload any file... – Christian C. Salvadó Jan 10 '10 at 05:22
  • Please tell me how can I modify this code so that it validate both the image type and size. thank you for answering – Selom Jan 11 '10 at 00:08
  • 1
    You can't really know anything but the name of the file from a file-input element (in modern browsers you can't even know the physical path of the file), this is due security policies, JavaScript is restricted and it cannot access the client file system. You should use a Flash-based or Java-based component like SWFUpload (http://swfupload.org/) or JUpload (http://sourceforge.net/projects/jupload/) if you want to make file-size restrictions on the client. – Christian C. Salvadó Jan 11 '10 at 01:40
8

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')
      }
 }
6

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'];
Mudaser Ali
  • 3,989
  • 3
  • 25
  • 27
4

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');
            }
        });
mzarrugh
  • 131
  • 1
  • 3
1

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.

Darrell Brogdon
  • 6,843
  • 9
  • 47
  • 62
  • 1
    Unfortunately the `accept` attribute is not really useful, it isn't used by any browser that I know... http://stackoverflow.com/questions/181214/file-input-accept-attribute-is-it-useful – Christian C. Salvadó Jan 10 '10 at 05:15
0

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.

pagboy
  • 15
  • 5
0

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.

Community
  • 1
  • 1
Dan F
  • 11,958
  • 3
  • 48
  • 72
0

<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"/>
Mohini
  • 268
  • 3
  • 15
0
const imageOnly = evt => {
  var fileName = document.getElementById("image").value;
  var idxDot = fileName.lastIndexOf(".") + 1;
  var extFile = fileName.substr(idxDot, fileName.length).toLowerCase();
  if (extFile=="jpg" || extFile=="jpeg" || extFile=="png"){
      return true;
  }else{
      alert("Only jpg/jpeg and png files are allowed!");
      document.getElementById("image").value = "";
  }   
}```

<input type="file" name="image" class="form-control" onchange="imageOnly('event')" id="image">
Mahedi Hasan Durjoy
  • 1,031
  • 13
  • 17