jQuery 验证 - 类型错误未定义

jQuery validate - TypeError undefined

我正在按照 jQuery 验证页面中的默认示例进行操作,但遇到了以下错误:

Uncaught TypeError: undefined is not a function

这一行:

$('form').validate().on('submit', function(e) {

当我尝试提交一个空表单时,我可以看到默认消息被按预期触发,但是,当我提交填写的表单时,没有发送任何内容。

没有 .validate() 表单提交正常。

是什么原因导致此错误和完成的表单无法使用 .validate() 通过?

html

<form id="form1" action="#" method="post">
    <label>Name:</label>
    <input type="text" minlength="2" name="name" required>

    <label>Class Id:</label>
    <input type="text" minlength="2" name="class" required>

    <p><button type="submit">Submit</button></p>
</form>

<script src="../js/jquery-1.11.2.min.js" type="text/javascript"></script>
<script src="../js/jquery.validate.min.js" type="text/javascript"></script>

jquery

(function() {
$('form').validate().on('submit', function(e) { 
    e.preventDefault(); 
    $.post('create.php', $(this).serialize(), function() { 
        console.log('Submission entered');
        window.location = 'contact_form.html'; 
    });
})
})();

您的代码...

$('form').validate().on('submit', function(e) { 
    e.preventDefault(); 
    $.post( .... );
});

我从未见过有人尝试将 jQuery .submit() 附加到 .validate() 方法。

为此只需使用插件的内置 submitHandler...

$('form').validate({
    submitHandler: function(form) {
        $.post('create.php', $(form).serialize(), function() { 
            console.log('Submission entered');
            window.location = 'contact_form.html'; 
        });
        return false;
    }
});

$(document).ready(function () {

    $('form').validate({
        submitHandler: function (form) {
            alert('valid form');
            /* // for demo
            $.post('create.php', $(form).serialize(), function () {
                console.log('Submission entered');
                window.location = 'contact_form.html';
            });
            */
            return false;
        }
    });
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script>
<form id="form1" action="#" method="post">
    <label>Name:</label>
    <input type="text" minlength="2" name="name" required>
    <label>Class Id:</label>
    <input type="text" minlength="2" name="class" required>
    <p>
        <button type="submit">Submit</button>
    </p>
</form>