开发者

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜