在AJAX请求提交表单之前进行表单验证

时间:2015-02-14 10:48:15

标签: javascript php jquery ajax forms

我希望在使用ajax提交之前验证表单。我在下面编写了代码,但是收到一条消息:"未捕获的ReferenceError:表单未定义"在chrome JS控制台中。该消息引用第25行,其中定义了form.validate函数。有任何建议如何修复它?

以下是表单标题:

            <form id="contactForm" name="contactForm">

感谢。

$(document).ready(function(){
    var form = document.querySelector("#contactForm");

    $("#submitButton").click(function() {
        if(form_validate()) {
            $.ajax({
                type:'GET',
                url: 'contact.php',
                data: $('#contactForm').serialize(),
                success: function(data) {
                    $("#result").html(data);
                }
            });
        }
        return false;
    });
});


/*
 * @return {boolean}
 */
    form_validate = function () {

        var name = document.forms["contactForm"]["user-name"].value;
        var email = document.forms["contactForm"]["email"].value;
        var phone = document.forms["contactForm"]["phone"].value;
        var message = document.forms["contactForm"]["message"].value;

        var validationAlert = document.getElementById("formValidationAlerts");
        var letterOnlyRegExp = /^[a-zA-Z\s]*$/;
        var emailRegExp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

        // Check if the fields full name, E-mail and message are filled.
        if ((name == null || name == "") ||
            (email == null || email == "") ||
            (message == null || message == "")) {
            validationAlert.innerHTML = "* Your Full Name, Your E-mail Address and Your Message are Required fields." +
                " Please fill all of them.";
            return false;
        }

        // Check if the full name is valid (English letters only).
        if (!(name.match(letterOnlyRegExp))) {
            validationAlert.innerHTML = "* Please Enter a Valid Name (English letters only).";
            return false;
        }

        // Check if the E-mail is valid.
        if (!(email.match(emailRegExp))) {
            validationAlert.innerHTML = "* Please Enter a Valid E-mail.";
            return false;
        }

        return true;
    };

编辑:我上传了更新后的代码。现在验证工作正常,但是在表单提交后我得到了这些错误(错误来自PHP文件)。

注意:未定义的索引:第7行/home/web/public_html/contact.php中的用户名

注意:未定义的索引:第8行的/home/web/public_html/contact.php中的电子邮件

注意:未定义索引:第9行/home/web/public_html/contact.php中的电话

注意:未定义的索引:第10行/home/web/public_html/contact.php中的公司

注意:未定义索引:第11行/home/web/public_html/contact.php中的消息

这是PHP文件:

<?php

        error_reporting(E_ALL);
        ini_set("display_errors", "On");

        $subject="Message from Web";
        $sender=$_POST["user-name"];
        $senderEmail=$_POST["email"];
        $senderPhone=$_POST["phone"];
        $senderCompany=$_POST["company"];
        $message=$_POST["message"];

        $mailBody="Name: $sender\nEmail: $senderEmail\nPhone: $senderPhone\nCompany: $senderCompany\n\n$message";

        mail('mymail@gmail.com', $mailBody, $sender);

        echo "Thank you! we will contact you soon.";

    ?>

2 个答案:

答案 0 :(得分:0)

尝试将form.validate重命名为form_validate,这应该可以解决您的错误。此外,您应该考虑从表单标题中删除method =“post”,因为您通过AJAX发送它(也使用GET !!)

答案 1 :(得分:0)

这一行似乎是本地表单变量:

var form = document.querySelector("#contactForm");

正在覆盖存储form.validate方法的全局表单对象。

尝试更改此行:

if(form.validate()) {

为:

if(window.form.validate()) {
相关问题