验证AJAX jquery提交表单

时间:2015-08-03 13:16:30

标签: jquery ajax validation

有没有办法在提交前验证我的脚本,即选择未填充的字段,不正确的电子邮件等

我目前正在使用表达式引擎的插件自由形式插件本身没有任何验证。因此我试图自己创建一个简单的功能。

我收到一条错误消息,上面写着以下内容

Uncaught TypeError: $(...).validate is not a function
下面的

是我的代码片段。

var form = $('#ajax-contact');
var formMessages = $('#form-messages');
$(form).submit(function (e) {
    e.preventDefault();
    var formData = $(form).serialize();
    // Submit the form using AJAX.
    $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: formData
    }).done(function (response) {
        if (response.success) {
            formMessages.removeClass('error').addClass('success').text("Thank you for submitting your details");
            $(".form-control").validate({
                rules: {
                    name: {
                        ranagelength: [2, 40],
                        required: true
                    },
                    email: {
                        ranagelength: [2, 40],
                        email: true,
                        required: true
                    },
                    errorClass: "error",
                    highlight: function (label) {
                        $(label).closest('.form-group').removeClass('has-success').addClass('has-error');
                    }
                }
            });
        } else {
            formMessages.removeClass("success").addClass("error").text("Oops, Please check your details");
        }
    }).fail(function (data) {
        // Make sure that the formMessages div has the 'error' class.
        $(formMessages).removeClass('success');
        $(formMessages).addClass('error');
        // Set the message text.
        if (data.responseText !== '') {
            $(formMessages).text(data.responseText);
        } else {
            $(formMessages).text('Oops! An error occured and your message could not be sent.');
        }
    });
});

1 个答案:

答案 0 :(得分:1)

您可以尝试jquery验证valid() method.Refer this链接并在就绪事件上定义您的规则,然后只检查如下。

$(document).ready(function () {
    $("#formid").validate({
        rules: {
            name: {
                ranagelength: [2, 40],
                required: true
            },
            email: {
                ranagelength: [2, 40],
                email: true,
                required: true
            },
            errorClass: "error",
            highlight: function (label) {
                $(label).closest('.form-group').removeClass('has-success').addClass('has-error');
            }
        }
    });
});

if ($("#formid").valid()) {
    //form is valid
} else {
    //forem is invalid
}