Restrict upload to file extensions in jQuery Validation

I want to perform validation with the jQuery Validation plugin for input type="file". I want to restrict file formats to doc,pdf,rtf, and docx.

Here is my code:

  $("#contact-form").validate({ 
          onfocusout: function(e) {
              this.element(e);
            },
        rules:{

            resume:{
                required:true,
                extension: "docx|rtf|doc|pdf"
            }

        },
    resume:{
                required:"input type is required",                  
                extension:"select valied input file format"
            }


    });

Upvotes: 6

Views: 44901

Answers (3)

kibus90
kibus90

Reputation: 315

Today I needed that script and I could not find.. I made own script (works almost for all browser, even IE). I would like notice I am beginner with jQuery, but I am trying to do something new:

Open JSfiddle

Here example:

$('#file').on('change', function() {
 var numb = $(this)[0].files[0].size/1024/1024; //count file size
var resultid = $(this).val().split(".");
var gettypeup  = resultid [resultid.length-1]; // take file type uploaded file
var filetype = $(this).attr('data-file_types'); // take allowed files from input
var allowedfiles = filetype.replace(/\|/g,', '); // string allowed file
var tolovercase = gettypeup.toLowerCase();
var filesize = 2; //2MB
var onlist = $(this).attr('data-file_types').indexOf(tolovercase) > -1;
var checkinputfile = $(this).attr('type');
numb = numb.toFixed(2);

if (onlist && numb <= filesize) {
			$('#alert').html('The file is ready to upload').removeAttr('class').addClass('xd2'); //file OK
   } else {
   if(numb >= filesize && onlist){
  $(this).val(''); //remove uploaded file
      $('#alert').html('Added file is too big \(' + numb + ' MB\) - max file size '+ filesize +' MB').removeAttr('class').addClass('xd'); //alert that file is too big, but type file is ok
      } else if(numb < filesize && !onlist) {
     $(this).val(''); //remove uploaded file
      $('#alert').html('An not allowed file format has been added \('+ gettypeup +') - allowed formats: ' + allowedfiles).removeAttr('class').addClass('xd'); //wrong type file
      } else if(!onlist) {
    $(this).val(''); //remove uploaded file
      $('#alert').html('An not allowed file format has been added \('+ gettypeup +') - allowed formats: ' + allowedfiles).removeAttr('class').addClass('xd'); //wrong type file
      }
   }
})
body{background:#fff}

#alert.xd{background:#ff9e9e; border:1px solid #ff0000;
color: #000;
padding:5px;
border-radius:10px}

#alert.xd2{background:#9effb3; border:1px solid #00de26;
color: #000;
padding:5px;
border-radius:10px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<br>
<input type="file" id="file" data-file_types="pdf|doc|docx|rtf|odt|jpg|jpeg">
<br><br>
Allowed files:<br><br>
<div id="allowed-files"></div>
<br><br>
<div id="allowed-size"></div>

<div id="alert"></div>
<script>
var title = $( "#file" ).attr( "data-file_types" ).replace(/\|/g,', ');
$( "#allowed-files" ).text( title );
</script>

If there is some faults in my code, please let me know :) Thank you.

Also I can answer for questions in the comments.

Upvotes: 0

Hemant Jadhav
Hemant Jadhav

Reputation: 105

If you don't want to create rule

just use accept attribute in input like below

<input type="file" accept="doc,pdf,rtf,docx"/>

Upvotes: 4

Sparky
Sparky

Reputation: 98748

You never explained the problem you're having with your code:

$("#contact-form").validate({ 
    onfocusout: function(e) {
        this.element(e);
    },
    rules:{
        resume:{
            required:true,
            extension: "docx|rtf|doc|pdf"
        }
    },
    resume:{
        required:"input type is required",                  
        extension:"select valied input file format"
    }
});

However, you're declaring messages without using the messages option. This is an error that would likely break the plugin, or at the least, your custom error messages would be ignored.

Your code should look like this...

$("#contact-form").validate({ 
    onfocusout: function(e) {  // this option is not needed
        this.element(e);       // this is the default behavior
    },
    rules:{
        resume:{
            required:true,
            extension: "docx|rtf|doc|pdf"
        }
    },
    messages: {  // <-- you must declare messages inside of "messages" option
        resume:{
            required:"input type is required",                  
            extension:"select valid input file format"
        }
    }
});

Working DEMO: http://jsfiddle.net/ZqxR2/

Upvotes: 15

Related Questions