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.

1

9 Answers 9

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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...
Please tell me how can I modify this code so that it validate both the image type and size. thank you for answering
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 (swfupload.org) or JUpload (sourceforge.net/projects/jupload) if you want to make file-size restrictions on the client.
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')
      }
 }

3 Comments

This is a really nice and simple solution! Thank you.
you could just use startsWith method ('image/');
Not working for JP2 format, giving empty file type
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'];

Comments

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

Comments

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.

1 Comment

Unfortunately the accept attribute is not really useful, it isn't used by any browser that I know... stackoverflow.com/questions/181214/…
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.

Comments

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.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.