简体   繁体   English

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

[英]Form validation before AJAX request to submit a form

I want to validate a form before it submitted with ajax. 我想在使用ajax提交之前验证表单。 I wrote the code below but I get a message: "Uncaught ReferenceError: form is not defined" in chrome JS console. 我在下面编写了代码,但是在chrome JS控制台中我收到了一条消息:“Uncaught ReferenceError:form not defined”。 The message refer to line 25, where the form.validate function is defined. 该消息引用第25行,其中定义了form.validate函数。 Any suggestion how to fix it? 有什么建议如何修复它?

Here is the form header: 这是表单标题:

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

Thanks. 谢谢。

$(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;
    };

EDIT: I uploaded the updated code. 编辑:我上传了更新的代码。 Now the validation works fine, but I got this errors after form submitted (the errors come from the PHP file). 现在验证工作正常,但是在表单提交后我得到了这个错误(错误来自PHP文件)。

Notice: Undefined index: user-name in /home/web/public_html/contact.php on line 7 注意:未定义的索引:第7行的/home/web/public_html/contact.php中的用户名

Notice: Undefined index: email in /home/web/public_html/contact.php on line 8 注意:未定义的索引:第8行的/home/web/public_html/contact.php中的电子邮件

Notice: Undefined index: phone in /home/web/public_html/contact.php on line 9 注意:未定义索引:第9行/home/web/public_html/contact.php中的电话

Notice: Undefined index: company in /home/web/public_html/contact.php on line 10 注意:未定义的索引:第10行/home/web/public_html/contact.php中的公司

Notice: Undefined index: message in /home/web/public_html/contact.php on line 11 注意:未定义索引:第11行/home/web/public_html/contact.php中的消息

here is the PHP file: 这是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.";

    ?>

Just try to rename form.validate to form_validate and this should fix your error. 只是尝试将form.validate重命名为form_validate,这应该可以解决您的错误。 Also you should consider to remove method="post" from form headers since you are sending it through AJAX (using GET also!!) 此外,您应该考虑从表单标题中删除method =“post”,因为您通过AJAX发送它(使用GET也!!)

It would appear that the local form variable in this line: 看来这行中的本地表单变量:

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

is overriding your global form object for which the form.validate method is stored in. 覆盖存储form.validate方法的全局表单对象。

Try changing this line: 尝试更改此行:

if(form.validate()) {

to: 至:

if(window.form.validate()) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM