Cant get google recaptcha v2 to prevent form submission

11,770

Solution 1

I use this which works for me. Put a js function in your form submit to validate the re-captcha:

<form action="/sign-visitors-log/" method="post" id="VisitorsLogForm" onsubmit="return validateRecaptcha();">

Then some js to stop the form submit if the user didn't tick the check box:

function validateRecaptcha() {
    var response = grecaptcha.getResponse();
    if (response.length === 0) {
        alert("not validated");
        return false;
    } else {
        alert("validated");
        return true;
    }
}

You can swap out the alerts for toast or as you are doing some elements on the page.

HTH

Solution 2

In a separate js file (at least: no inline call to a function), you have to check if the captcha can validate. Like so:

  jquery('form').on('submit',function(e){

      if(grecaptcha.getResponse() === "") {
        e.preventDefault();
        alert('Error: \n please validate the Captcha test');
     }

  });

You don't have to check if the test passive as true, you have already prevented the form to be sent with this method.

Share:
11,770
Admin
Author by

Admin

Updated on July 21, 2022

Comments

  • Admin
    Admin almost 2 years

    So I can successfully get the captcha to validate, using the following code.

      </p>
    <?php
    if(isset($_POST['g-recaptcha-response'])){
    echo verify($_POST['g-recaptcha-response']);
    
    }
    
    function verify($response) {
    $ip = $_SERVER['blank']; //server Ip
    $key="secretkey"; // Secret key
    
    //Build up the url
    $url = 'https://www.google.com/recaptcha/api/siteverify';
    $full_url = $url.'?secret='.$key.'&response='.$response.'&remoteip='.$ip;
    
    //Get the response back decode the json
    $data = json_decode(file_get_contents($full_url));
    //Return true or false, based on users input
    if(isset($data->success) && $data->success == true) {
    return True;
    }
    return False;
    }
    ?>
    <p style="text-align: justify;">
    
    <script type="text/javascript">
     function verify(){
     var serializedValues = jQuery("#infoForm").serialize();
     jQuery.ajax({ type: 'POST',url:"verify.php",data: serializedValues,success:function(result){
     if(result){
     $('#show').html('Your Form Successfully Submitted');
     $('.formwrap').hide(result);
     return true;
     }
     }});
     $('#show').html('Please Enter Valid Captcha');
     return false;
    }
     var onloadCallback = function() {
     grecaptcha.render('captcha_ele', {
     'sitekey' : 'Enter Your Site Key Here', // Site key
     });
     };
     </script>
    

    However, when I click submit, regardless of what the captcha says, form will still submit. My email form process is as follows...

    <!-- language: lang-css -->
    
    $("#blank").submit(function() {
        $.post('assets/php/email-process.php', {name: $('#name').val(), email: $('#email').val(), message: $('#message').val(), myFormSubmitted: 'yes'}, 
        function(data) {
            $("#formResponse").html(data).fadeIn('100');
            $('#name, #email, #message').val(''); /* Clear the inputs */
        }, 'text');
        return false;
    }); 
    
    <?php
    if ($_POST['leaveblank'] != '' or $_POST['dontchange'] != 'http://') {
       // display message that the form submission was rejected
    }
    else {
       // accept form submission
    $to = 'info@blank'; // Replace with your email  
        $subject = 'Message from website visitor'; // Replace with your $subject
        $headers = 'From: ' . $_POST['email'] . "\r\n" . 'Reply-To: ' . $_POST['email'];    
    
        $message = 'Name: ' . $_POST['name'] . "\n" .
                   'E-mail: ' . $_POST['email'] . "\n" .
                   'Subject: ' . $_POST['subject'] . "\n" .
                   'Message: ' . $_POST['message'];
    
        mail($to, $subject, $message, $headers);    
        if( $_POST['copy'] == 'on' )
        {
            mail($_POST['email'], $subject, $message, $headers);
        }
        echo 'Thank you for your Email. We will get in touch with you very soon.';
    
    }
    
    
    ?>