简体   繁体   中英

Form validation before AJAX request to submit a form

I want to validate a form before it submitted with ajax. I wrote the code below but I get a message: "Uncaught ReferenceError: form is not defined" in chrome JS console. The message refer to line 25, where the form.validate function is defined. 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).

Notice: Undefined index: user-name in /home/web/public_html/contact.php on line 7

Notice: Undefined index: email in /home/web/public_html/contact.php on line 8

Notice: Undefined index: phone in /home/web/public_html/contact.php on line 9

Notice: Undefined index: company in /home/web/public_html/contact.php on line 10

Notice: Undefined index: message in /home/web/public_html/contact.php on line 11

here is the PHP file:

<?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. Also you should consider to remove method="post" from form headers since you are sending it through AJAX (using GET also!!)

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.

Try changing this line:

if(form.validate()) {

to:

if(window.form.validate()) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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