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.

Answered By – Christian C. Salvadó

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published