jquery validate accept method - TypeError: Cannot read property 'call' of undefined

非 Y 不嫁゛ 提交于 2021-02-16 09:50:30

问题


I want to check the upload file type using the validate plugin.

But I got the following error message:

Uncaught TypeError: Cannot read property 'call' of undefined.
Exception occurred when checking element file, check the 'accept' method.

Here is my form.

<form id="upload" enctype="multipart/form-data">
    <div class="control-group">
        <div class="controls">
            <input id="file" name="file" type="file">
        </div>
        <div class="form-group">
            <button class="btn btn-primary" onclick="Submit()" type="button">Submit</button>
        </div>
    </div>
</form>

And here is my JavaScript:

var Submit=function(){
    var validator = $('#upload').validate({
        rules:{
            file: {
                required: true,
                accept: "audio/*, video/*"
            }
        },
        message: {
            file:"Invalid file type"
        }
   });

    validator.form();
}

回答1:


To use the "accept" method you'll need to include the jQuery Validate additional methods file. Simply include it after your validate file:

<script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>

Then try initiating your validator like this instead:

$(document).ready(function(){
    $("#upload").validate({
        ...settings...
    });
});

And remove the onClick and type="button" attribute from your button.

Here are the docs:

http://jqueryvalidation.org/validate/




回答2:


I had same issue but I got a solution I have added the below code in script above jquery validation script

$.validator.addMethod('filesize', function (value, element, param) {
    return this.optional(element) || (element.files[0].size <= param)
}, 'File size must be less than {0}');

After that you have to add your own validation script

var Submit=function(){
    var validator = $('#upload').validate({
        rules:{
            file: {
                required: true,
                accept: "audio/*, video/*"
            }
        },
        message: {
            file:"Invalid file type"
        }
   });

    validator.form();
}


来源:https://stackoverflow.com/questions/33531055/jquery-validate-accept-method-typeerror-cannot-read-property-call-of-undefi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!