如何使用jQuery / Ajax / PHP显示所有验证错误消息?

时间:2017-09-18 05:49:57

标签: javascript php jquery ajax validation

我使用以下Javascript代码验证表单:

timerRunning

在form-validation.php页面中,我有以下代码:

$("#contactForm").submit(function(e) {
    e.preventDefault();
    formData = $(this).serialize();
    $.ajax({
        url : 'form-validation.php',        
        type : 'POST',
        dataType : 'json',
        data : formData,
        beforeSend : function () {
            $("#form-submit").text('Validation...');
            $("#form-submit").prop('disabled', true);
        }, 
        success : function ( result ) {
            $("#form-submit").text('Send Message');
            $("#form-submit").prop('disabled', false);  
            for ( x in result ) {   
                alert('key: ' + x + '\n' + 'value: ' + result[x]);                  
                $("#formResult").html('<div class="alert alert-danger">'+result[x]+'</div>');
                if( result['error'] == false ) {
                    $("#formResult").html('<div class="alert alert-danger">Your message has been sent. I will contact with you asap.</div>'); 
                    $('#contactForm')[0].reset();   
                    setTimeout(function () {
                        window.location.href = 'mysite.com/portfolio/contact.php';
                    }, 5000);
                }
            }

        }
    });
});

现在,我有以下问题:

  1. 如果表单有任何验证错误,它会逐个显示错误消息,而不是全部显示。为什么?

  2. 验证从最后一个输入字段开始。我的意思是在我的表单中我有5个输入字段,名称,电子邮件,主题,消息,谷歌验证码。现在,错误消息显示从谷歌验证码,消息,主题,电子邮件和名称,而不是名称,电子邮件,主题,消息,谷歌验证码。

  3. 现在重新验证google验证码我在成功提交表单后重新加载页面。有没有其他方法重新验证谷歌验证码而无需重新加载页面?

  4. 非常感谢!

4 个答案:

答案 0 :(得分:1)

这是因为您的数据[&#39; msg&#39;]会在多个错误情况下覆盖。 请以这种方式在数组中返回您的消息..

if( isset($formName, $formEmail, $formSubject, $formMessage, $googleCaptcha) ) {
if( empty($formName) && empty($formEmail) && empty($formSubject) && empty($formMessage) && empty($googleCaptcha) ) {
    $data[]    = 'All fields are required';        
    $data['error']      = true;
} else {
    if( empty($formName)) {
        $data[]    = 'Your name required';
        $data['error']          = true;
    } elseif( strlen($formName) < 2 || strlen($formName) > 20 ) {
        $data[]    = 'Your name should be 2-20 characters long';
        $data['error']          = true;
    } elseif( is_numeric($formName)) {
        $data[]    = 'Your name must be alphabic characters';
        $data['error']          = true;
    }

    if( empty($formEmail)) {
        $data[]    = 'Your email address required';
        $data['error']          = true;
    } elseif( !filter_var($formEmail, FILTER_VALIDATE_EMAIL)) {
        $data[]    = 'Your email is incorrect';
        $data['error']          = true;
    }

    if( empty($formSubject)) {
        $data[]    = 'Your message subject required';
        $data['error']  = true;
    } elseif( strlen($formSubject) < 2 || strlen($formSubject) > 500 ) {
        $data[]    = 'Your message subject should be 2-500 characters long';
        $data['error']      = true;
    } elseif( is_numeric($formSubject)) {
        $data[]    = 'Your message subject must be alphabic characters';
        $data['error']      = true;
    }

    if( empty($formMessage)) {
        $data[]    = 'Your message required';
        $data['error']      = true;
    } elseif( strlen($formMessage) < 2 || strlen($formMessage) > 1500 ) {
        $data[]    = 'Your message should be 2-1500 characters long';
        $data['error']      = true;
    } elseif( is_numeric($formMessage)) {
        $data[]    = 'Your message must be alphabic characters';
        $data['error']      = true;
    }

    if( empty($googleCaptcha) ) {
        $data[]    = 'Invalid captcha';
        $data['error']      = true;
    } elseif(!$responseData->success) {
        $data[]    = 'Captcha verfication failed';
        $data['error']      = true;
    }
}

答案 1 :(得分:0)

  1. 使用array_push()存储错误消息。按照文档 array_push()

  2. 尝试这个问题的答案

    How to Reload ReCaptcha using JavaScript?

答案 2 :(得分:0)

您可以使用Ahman的代码,或使用此示例代码

$formName       = htmlspecialchars($_POST['form-name']);
$formEmail      = htmlspecialchars($_POST['form-email']);
$formSubje    ct    = htmlspecialchars($_POST['form-subject']);
$formMessage    = htmlspecialchars($_POST['form-message']);
$googleCaptcha  = htmlspecialchars($_POST['g-recaptcha-response']);
$secret         = 'my secret code';
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$googleCaptcha);
$responseData   = json_decode($verifyResponse);

$data           = array();
$data['error']  = false;

if( isset($formName, $formEmail, $formSubject, $formMessage, $googleCaptcha) ) {
    if( empty($formName)) {
        $data['form-name']['msg']    = 'Your name required';
        $data['form-name']['error']          = true;
    } elseif( strlen($formName) < 2 || strlen($formName) > 20 ) {
        $data['form-name']['msg']    = 'Your name should be 2-20 characters long';
        $data['form-name']['error']          = true;
    } elseif( is_numeric($formName)) {
        $data['form-name']['msg']    = 'Your name must be alphabic characters';
        $data['form-name']['error']          = true;
    }

    if( empty($formEmail)) {
        $data['form-email']['msg']    = 'Your email address required';
        $data['form-email']['error']          = true;
    } elseif( !filter_var($formEmail, FILTER_VALIDATE_EMAIL)) {
        $data['form-email']['msg']    = 'Your email is incorrect';
        $data['form-email']['error']          = true;
    }
    ....
}

if( $data['error']  === false) {

    $to = "mysite@gmail.com";
    $subject = "Contac Form- Creativeartbd.com";

    $message = "<b>$formMessage</b>";

    $header = "From:mysite.com.com \r\n";
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-type: text/html\r\n";

    $retval = mail ($to,$subject,$message,$header);
    if( $retval ) {
        $data['send-mail']['msg'] = 'Your message has been sent. I will contact with you asap.';
        $data['send-mail']['error']      = false;
    } else {
        $data['send-mail']['msg'] = "Your message didn't sent";
        $dat['send-mail']a['error']      = true;
    }
    }
}    

echo json_encode( $data );

在JS部分中,您可以解析json,查看键,然后显示每个字段的错误

答案 3 :(得分:0)

jquery:index.php

<script type="text/javascript">
$(document).ready(function(){
    $("#contactForm").submit(function(e) {
        e.preventDefault();

        $("#formResult").html("");

        formData = $(this).serialize();

        $.ajax({
            url : 'form-validation.php',        
            type : 'POST',
            dataType : 'json',
            data : formData,
            cache : false,
            beforeSend : function () {
                $("#form-submit").text('Validation...');
                $("#form-submit").prop('disabled', true);
            }, 
            success : function ( result ) {
                $("#form-submit").text('Send Message');
                $("#form-submit").prop('disabled', false);

                /* for(x in result['error']){
                    alert('key: ' + x + '\n' + 'value: ' + result['error'][x]);
                } */

                if( result['success'] == true ) {
                    //$('#contactForm')[0].reset();
                    $("#formResult").html('<div class="alert alert-danger">'+result['msg'][0]+'</div>'); 
                    //$("#formResult").html('<div class="alert alert-danger">Your message has been sent. I will contact with you asap.</div>'); 

                    var i = 5;
                    setInterval(function () {
                        i--;
                        $("#counter").html("you'll be redirect in " +i+ " seconds");
                    }, 1000);

                    setTimeout(function () {
                        window.location.href = 'mysite.com/portfolio/contact.php';
                    }, i*1000);

                }else{

                    for(x in result['msg']){
                        //alert('key: ' + x + '\n' + 'value: ' + result['msg'][x]);
                        $("#formResult").append('<div class="alert alert-danger">'+result['msg'][x]+'</div>'+"\n");
                    }
                }

            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status + "\n" +thrownError);
            }
        });
    });
});
</script>

<强>形状validation.php

<?php

$formName       = htmlspecialchars($_POST['form-name']);
$formEmail      = htmlspecialchars($_POST['form-email']);
$formSubject    = htmlspecialchars($_POST['form-subject']);
$formMessage    = htmlspecialchars($_POST['form-message']);
$googleCaptcha  = htmlspecialchars($_POST['g-recaptcha-response']);
$secret         = 'my secret code';
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$googleCaptcha);
//$verifyResponse = '{"success":1}';
$responseData   = json_decode($verifyResponse);

$data           = array();
$data['error']  = false;
$data['success'] = false;

if( isset($formName, $formEmail, $formSubject, $formMessage, $googleCaptcha) ) {
    if( empty($formName) && empty($formEmail) && empty($formSubject) && empty($formMessage) && empty($googleCaptcha) ) {
        $data['msg'][]    = 'All fields are required';        
        $data['error']      = true;
    } else {
        if( empty($formName)) {
            $data['msg'][]    = 'Your name required';
            $data['error']          = true;
        } elseif( strlen($formName) < 2 || strlen($formName) > 20 ) {
            $data['msg'][]    = 'Your name should be 2-20 characters long';
            $data['error']          = true;
        } elseif( is_numeric($formName)) {
            $data['msg'][]    = 'Your name must be alphabic characters';
            $data['error']          = true;
        }

        if( empty($formEmail)) {
            $data['msg'][]    = 'Your email address required';
            $data['error']          = true;
        } elseif( !filter_var($formEmail, FILTER_VALIDATE_EMAIL)) {
            $data['msg'][]    = 'Your email is incorrect';
            $data['error']          = true;
        }

        if( empty($formSubject)) {
            $data['msg'][]    = 'Your message subject required';
            $data['error']  = true;
        } elseif( strlen($formSubject) < 2 || strlen($formSubject) > 500 ) {
            $data['msg'][]    = 'Your message subject should be 2-500 characters long';
            $data['error']      = true;
        } elseif( is_numeric($formSubject)) {
            $data['msg'][]    = 'Your message subject must be alphabic characters';
            $data['error']      = true;
        }

        if( empty($formMessage)) {
            $data['msg'][]    = 'Your message required';
            $data['error']      = true;
        } elseif( strlen($formMessage) < 2 || strlen($formMessage) > 1500 ) {
            $data['msg'][]    = 'Your message should be 2-1500 characters long';
            $data['error']      = true;
        } elseif( is_numeric($formMessage)) {
            $data['msg'][]    = 'Your message must be alphabic characters';
            $data['error']      = true;
        }

        if( empty($googleCaptcha) ) {
            $data['msg'][]    = 'Invalid captcha';
            $data['error']      = true;
        } elseif(!$responseData->success) {
            $data['msg'][]    = 'Captcha verfication failed';
            $data['error']      = true;
        }
    }

    if( $data['error']  === false) {

        $to = "mysite@gmail.com";
        $subject = "Contac Form- Creativeartbd.com";

        $message = "<b>$formMessage</b>";       

        $header = "From:mysite.com.com \r\n";       
        $header .= "MIME-Version: 1.0\r\n";
        $header .= "Content-type: text/html\r\n";

        $retval = mail ($to,$subject,$message,$header);
        //$retval = true;
        if( $retval ) {
            $data['msg'][] = 'Your message has been sent. I will contact with you asap.';
            $data['success'] = true;
        } else {
            $data['msg'][] = "Your message didn't sent";
            $data['error'] = true;
        }       
    }
}
echo json_encode( $data );