How to validate a file input on client side (Javascript)

11,226

Solution 1

Try this:

 $("#pic").change(function() {

    var val = $(this).val();

    switch(val.substring(val.lastIndexOf('.') + 1).toLowerCase()){
        case 'gif': case 'jpg': case 'png':
            alert("an image");
            break;
        default:
            $(this).val('');
            // error message here
            alert("not an image");
            break;
    }
});

Solution 2

function startImageUpload(imageuploadform){

  var form = $(imageuploadform)
    , value = form.find('.fileImage').val()

  form.find('.imagef1_upload_process').css('visibility','visible')
  form.find('.imagef1_upload_form').css('visibility','hidden')

  if (!/\.(png|gif)$/.test(value)){
    return false
  }
  return true
}

The HTML specification also evolved to include an accept attribute:

<input type="file" accept="image/png,image/gif" />

(supported in Chrome, Firefox and Opera - IE10, Safari 6 in the near future)

Solution 3

You can check like so...

var validExtensions = ['png', 'gif'],
    validExtensionSupplied = $.inArray(
           ($('.fileImage').val().match(/\.(.*?)]\s*$/) || [])[1],
           validExtensions) != -1;

Alternatively, you can validate by MIME type by checking the $('.fileImage').prop('files')[0].type.

Share:
11,226
user1324106
Author by

user1324106

Updated on June 24, 2022

Comments

  • user1324106
    user1324106 almost 2 years

    I have a form stored in a javascript variable below:

    var $fileImage = $("<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='startImageUpload(this);' class='imageuploadform' >" + 
    "<label> Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/>" +
    "<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label></form>
    

    Now as you can see when the user clicks on the submit button, it submits to the 'startImageUpload' function which is below:

    function startImageUpload(imageuploadform){
      $(imageuploadform).find('.imagef1_upload_process').css('visibility','visible');
      $(imageuploadform).find('.imagef1_upload_form').css('visibility','hidden');
      sourceImageForm = imageuploadform;
          return true;
    }
    

    What it does is that when the user clicks on submit, it displays a loading bar and uploads the form.

    Now what my question is that I want to perform a simple javascript validation where when the user clicks on the submit button in the form, it will check if the file either a 'png' or 'gif' file type. If it is correct file type, then display the loading bar and upload the form. If the file type is incorrect, then show a n alert stating file type is incorrect but don't show the loading bar and do not upload the form.

    Does anyone know how this can be coded. It is so I can use the example from one of your answers to then expand on it and use the javascript to validate on more file types and also file size so it will be very helpful if somebody can please help me.

    Thank You

  • elclanrs
    elclanrs about 12 years
    I was thinking something like this too. Just for fun you could use the tilde operator to compare to -1 and cast a boolean with !!. Less readable but a bit more compact. !!~$.inArray(($('.fileImage').val().match(/\.(.*?)$/) || [])[1], validExtensions)