1

I am using following Javascript code to validate a form:

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

        }
    });
});

In form-validation.php page I have following code:

<?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);
$responseData   = json_decode($verifyResponse);

$data           = array();
$data['error']  = 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 = "[email protected]";
        $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['msg'] = 'Your message has been sent. I will contact with you asap.';
            $data['error']      = false;
        } else {
            $data['msg'] = "Your message didn't sent";
            $data['error']      = true;
        }       
    }
}

echo json_encode( $data );

Now, I have following question:

  1. If the form has any validation error it's showing the error message one by one instead of showing all. why?

  2. The validation is starting from the last input field. I mean in my form I have 5 input fields which is name, email, subject, message, google captcha. Now the error message is showing from the google captcha, message, subject, email and name instead of name, email, subject, message, google captcha.

  3. Now to re-validate the google captcha I am reloading the page after successfully submit the form. Is there any other way to re-validate the google captcha without reload the page?

Thanks a lot!

5
  • Basically, the returning $data contains only "msg" and "error", then it could not represent for errors of all fields. You have to make the $data more informative. And that why the error is showing for the last one first. Commented Sep 18, 2017 at 5:57
  • @TuanDuong Thanks for your reply. Do you have any idea how can I do this? Commented Sep 18, 2017 at 5:58
  • Create an array of all errors and convert it into json and display all those messages from ajax Commented Sep 18, 2017 at 5:58
  • @ShibbirAhmed You have to return $data with fields-as-keys, then in the JS/HTML, you can on/off the errors based on that fields-as-keys. I will write the sample code as answer. Commented Sep 18, 2017 at 6:07
  • You should use framework Commented Sep 18, 2017 at 6:17

4 Answers 4

1

This is because your data['msg'] is overwritting in multiple error case. Please return your message in this way in array..

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;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Ahmad Let me try with this.
It's not working. When I submit the form the submit button is showing me Validating... No error message is showing.
well, now it's showing all message in the console log but now on web page. Is there anything in JS I need to change?
0
  1. Use array_push() to store error messages. Follow documentation array_push()

  2. Try the answer in this question

    How to Reload ReCaptcha using JavaScript?

Comments

0

You can use Ahman's code, or using this sample code

$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 = "[email protected]";
    $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 );

In the JS part, you could parse the json, look into keys, then show the error for each field

6 Comments

I'm using Ahmed reply but it's not showing the validation message on webpage but I can see it in console log. I am using followiing js code:
for ( var x in result) { alert( result[x] ); $("#formResult").html('<div class="alert alert-danger">'+result[x]+'</div>'); }
@ShibbirAhmed: Ahmed code returns error message as array, you have to loop in result[x] to show the detail
If I use result[x] then it returns true not details!
Using x in my loop is getting the object property. I need to get the details like...0,1,2,3... as the return value is showing like that: {0: "All fields are required", error: true}
|
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>

form-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 = "[email protected]";
        $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 );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.