Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 997
Selom Avatar asked Nov 28 '22 20:11

Selom


2 Answers

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.

like image 196
Christian C. Salvadó Avatar answered Dec 05 '22 00:12

Christian C. Salvadó


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'];
like image 20
Mudaser Ali Avatar answered Dec 05 '22 00:12

Mudaser Ali