JQuery Validate input file type
jquery, jquery-validate
Solution
One the elements are added, use the rules method to add the rules
//bug fixed thanks to @Sparky
$('input[name^="fileupload"]').each(function () {
$(this).rules('add', {
required: true,
accept: "image/jpeg, image/pjpeg"
})
})
Demo: Fiddle
Update
var filenumber = 1;
$("#AddFile").click(function () { //User clicks button #AddFile
var $li = $('<li><input type="file" name="FileUpload' + filenumber + '" id="FileUpload' + filenumber + '" required=""/> <a href="#" class="RemoveFileUpload">Remove</a></li>').prependTo("#FileUploader");
$('#FileUpload' + filenumber).rules('add', {
required: true,
accept: "image/jpeg, image/pjpeg"
})
filenumber++;
return false;
});
Problem
I have a form that can have 0-hundreds of `<input type="file">` elements. I have named them sequentially depending on how many are dynamically added to the page. For example: ``` <input type="file" required="" name="fileupload1" id="fileupload1"> <input type="file" required="" name="fileupload2" id="fileupload2"> <input type="file" required="" name="fileupload3" id="fileupload3"> <input type="file" required="" name="fileupload999" id="fileupload999"> ``` In my JQuery I want to validate these inputs on acceptable MIME/file type. Like this: ``` $("#formNew").validate({ rules: { fileupload: { required: true, accept: "image/jpeg, image/pjpeg" } } ``` Immediately my problem is that the `name` attribute of the input file elements is dynamic. It has to be dynamic so that my web application can deal with each upload correctly. So obviously using "fileupload" isn't going to work in the rules section. How do I set the rules for all inputs which have a name like "fileupload"? This is the code that dynamically adds the inputs: ``` var filenumber = 1; $("#AddFile").click(function () { //User clicks button #AddFile $('<li><input type="file" name="FileUpload' + filenumber + '" id="FileUpload' + filenumber + '" required=""/> <a href="#" class="RemoveFileUpload">Remove</a></li>').prependTo("#FileUploader"); filenumber++; return false; }); $("#FileUploader").on('click', '.RemoveFileUpload', function () { //Remove input if (filenumber > 0) { $(this).parent('li').remove(); filenumber--; } return false; }); ```