具有 jquery 验证的 Materializecss 不起作用

Materializecss with jquery validation not working

HTML 标记;

<div id="address" class="col s12">
    <div class="row">
        <form method="post" action="" id="addressDetails">
            <div class="input-field col s6">
                <textarea id="lAddress" name = 'lAddress' minlength='20' maxlength='100' class="materialize-textarea" class="validate" required length="100"></textarea>
                <label for="lAddress" data-error="Must be between 20 to 100 Characters">Local Address</label>
            </div>
            <div class="input-field col s6">
                <textarea id="pAddress" name = 'pAddress' minlength='20' maxlength='100' class="materialize-textarea" class="validate" required length="100"></textarea>
                <label for="pAddress" data-error="Must be between 20 to 100 Characters">Permanent Address</label>
            </div>
        </form>
    </div>
    <div class="row center-align">
        <button type="submit" name="submitAddress" form="addressDetails" class="waves-effect waves-light light-blue darken-1 btn updateProfile">Save Address Details</button>
    </div>
</div>

JavaScript代码:

function updateProfile(event) {
    console.log(this);
    event.preventDefault();
    form = $(this).closest('.col.s12').find('form');
    $.ajax('profile/updateProfile.php', {
        type: "POST",
        dataType: "json",
        data: form.serialize(),
        success: function(result) {
            Materialize.toast(result.message, 4000);
        },
        error: function() {
            Materialize.toast("Failed: Please contact admin.", 4000);
        },
        timeout: 5000
    });
}

$(document).ready(function() {
    $("button.updateProfile").on('click', updateProfile);
});

之前正常的表单提交验证是有效的。但是现在有了 jQuery AJAX 请求,我可以发送数据,但是当表单无效时,它会以红色显示错误,但它会接受有错误的表单。

当我使用 $("button.updateProfile").on('sumbit', updateProfile); 时,它正在验证但它正在重新加载页面并且 preventDefault 不起作用。

$("button.updateProfile").on('click', updateProfile);

这将不会在物化验证的帮助下进行验证。你必须寻找 submit.

再次用submit会有问题,不是在form里找submission。

$("button.updateProfile").on('sumbit', updateProfile);

代替按钮使用表单,然后将查找表单提交。像这样

$("form").on('submit', updateProfile);

这将非常有效。

所以请记住,无论何时提交表单,都要检查是否在表单上而不是在提交按钮上提交。