Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 980
user1324106 Avatar asked Apr 12 '12 23:04

user1324106


People also ask

How do you validate a file type in JavaScript?

Using JavaScript, you can easily check the selected file extension with allowed file extensions and can restrict the user to upload only the allowed file types. For this we will use fileValidation() function. We will create fileValidation() function that contains the complete file type validation code.

Can we validate client-side form in JavaScript?

JavaScript provides facility to validate the form on the client-side so data processing will be faster than server-side validation. Most of the web developers prefer JavaScript form validation. Through JavaScript, we can validate name, password, email, date, mobile numbers and more fields.

Does JavaScript validate user input?

Client side validation occurs using HTML5 attributes and client side JavaScript. You may have noticed that in some forms, as soon as you enter an invalid email address, the form gives an error "Please enter a valid email". This immediate type of validation is usually done via client side JavaScript.


3 Answers

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)

like image 79
Ricardo Tomasi Avatar answered Oct 23 '22 05:10

Ricardo Tomasi


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.

like image 21
alex Avatar answered Oct 23 '22 04:10

alex


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;
    }
});
like image 20
coder Avatar answered Oct 23 '22 05:10

coder