Home >JavaScript >Introduction to JavaScript >File type validation with jQuery

File type validation with jQuery

As part of protecting forms against spam or malicious code, you also need to validate the extension of the file the user uploads. If you allow, for example, only images, a robot has no way to upload dangerous scripts.

<div class="form_block_1_4">
<span class="form_label">Attachment 1</span>
<input class="form_file_def" type="file" name="attachment_file[]" value="" />
</div>
<div class="form_block_1_4">
<span class="form_label">Attachment 2</span>
<input class="form_file_def" type="file" name="attachment_file[]" value="" />
</div>
<div class="form_block_1_4">
<span class="form_label">Attachment 3</span>
<input class="form_file_def" type="file" name="attachment_file[]" value="" />
</div>
<div class="form_block_1_4">
<span class="form_label">Attachment 4</span>
<input class="form_file_def" type="file" name="attachment_file[]" value="" />
</div>
<script>
// message and ok are variables of your form validation
var message = "";
var ok = true;
$( 'input[name="attachment_file[]"]' ).each(function( index ) {
  var file_number = index+1;
  var file_value = $( this ).val();
  if( file_value != "" ){
    var regex = /\.(jpg|jpeg|pdf)$/i;
    // other extensions, for example: /\.(docx|doc|pdf|xml|bmp|ppt|xls)$/i
    if(!(regex.test(file_value))) {
      $(this).val('');
      message = message+"File "+file_number+" has a wrong format (allowed are jpg, jpeg, pdf)!\n";
      ok = false;
    }
  }
});
</script>

Note: the check in the browser is only for the comfort of the user and is easy to get around. The file type must always be checked on the server (in PHP) as well – only that really protects the website.