问题
I tried using jquery validate but i've spent more than 4 hours to search how to solve my problem but couldn't find it. The problem is when I tried using jquery validate for filesize in multidimensional array, it doesn't work. It can still submit the form and not showing the error message.
Here is it my field
var numberIncr = 1;
$('#add-berkas').click(function () {
var box_html = $('<div class="text-box form-group row">\n' +
' <div class="col-sm-8">\n' +
' <input type="text" name="berkas['+numberIncr+'][nama]" placeholder="Nama File" class="form-control" required>\n' +
' </div>\n' +
' <div class="col-sm-4">\n' +
' <input type="file" name="berkas['+numberIncr+'][file]" id="berkasfile'+numberIncr+'" accept="application/pdf" required/>\n' +
' <button id="remove-berkas" class="btn btn-sm btn-danger remove-box" type="button"><i class="fa fa-trash"></i></button>\n' +
' </div>\n' +
' </div>');
$('.text-box:last').after(box_html);
box_html.fadeIn('slow');
numberIncr++;
});
And this is the validate
$.validator.addMethod('filesize', function (value, element, param) {
return this.optional(element) || (element.files[0].size <= param)
}, 'File size must be less than {0}');
var berkas = $('input[name^="berkas"]');
berkas.filter('input[name$="[file]"]').each(function() {
$(this).rules("add", {
extension: "pdf", filesize:1048576,
messages: "Berkas must be PDF and less than 1MB"
});
});
$("#form").validate({
rules: {
surat: {extension: "pdf", filesize: 1048576, },
},
messages: {
surat: "Surat must be PDF and less than 1MB",
},
errorPlacement: function(error,element){
showErrorMessage(error.text());
},
submitHandler: function(form) {
form.submit();
},
highlight: function(element, errorClass) {
return false;
}
});
回答1:
Your problem is caused by presumably only calling this code once on page load, when the fields don't yet exist...
berkas.filter('input[name$="[file]"]').each(function() {
$(this).rules("add", {
extension: "pdf", filesize:1048576,
messages: "Berkas must be PDF and less than 1MB"
});
});
There are no matching fields at the time you call this code. The whole point of this method is for you to dynamically add the rules after you create each field.
You must call it immediately after adding a new field. Put it inside the click
handler near the bottom.
var numberIncr = 1;
$('#add-berkas').click(function () {
var box_html = $('<div class="text-box form-group row">\n' +
.....
' </div>');
$('.text-box:last').after(box_html);
box_html.fadeIn('slow');
// add rules to new field here
$('[name="berkas[' + numberIncr + '][file]"]').rules("add", {
extension: "pdf", filesize:1048576,
messages: "Berkas must be PDF and less than 1MB"
});
numberIncr++;
});
You wouldn't need an .each()
since you only create one field on each click. Just target the new field and add the rule.
来源:https://stackoverflow.com/questions/64663160/jquery-validate-filesize-in-multidimensional-array-dynamically