1

我有一个不需要验证的文件输入框。但是如果输入框不为空,那么我希望执行文件类型和文件大小的验证。

jQuery(document).ready(function(){

jQuery.validator.addMethod("accept", function(value, element, param) {
    return value.match(new RegExp("." + param + "$"));
});

jQuery.validator.addMethod('filesize', function(value, element, param) {
    return this.optional(element) || (element.files[0].size <= param) 
});


jQuery('#adminform').validate({

    rules: {

        resume: {
                required: false,
                accept: "(doc|docx|pdf)",
                filesize: 1024 //1048576
        }
    },
......................
    resume: {
        accept: "File type not supported",
        filesize: "File cannot be more than 1MB!"
    },

现在的问题是,即使我不提供任何输入并将其留空,我也会执行“接受”规则,即我收到消息“不支持文件类型”

4

2 回答 2

0

试试这个..非空检查确保如果字段留空,则不会执行验证

$('input[type="file"]').on("change", function() { 
if ($this.val() !== '') { 
    //do validation stuff here!!
} 
});
于 2012-12-26T05:50:02.683 回答
0

如果这有帮助,试试这个:

$("#commentForm").validate({
rules: {
    name: "required",
    file: "required",
    name: {
        required: true,
        minlength: 2
    },
    file: {
        required: false,
        minlength: 5
    }
},
messages: {
    name: {
        required: "Please enter a username",
        minlength: "Your username must consist of at least 2 characters"
    },
    file: {
        required: "Please select a file",
        minlength: "Your password must be at least 5 characters long"
    }
},
submitHandler: function(form) {
    if ($('#cfile').val() != "") {
        $("#commentForm").validate({
            rules: {
                file: "required",
                file: {
                    required: true,
                    minlength: 5
                }
            },
            messages: {
                file: {
                    required: "Please select a file"
                }
            }
        });
        $(form).submit();
    } else {
        alert('file missing.');
    }
}

});
于 2012-12-26T06:35:19.200 回答