IanWatson
IanWatson

Reputation: 1739

Google reCaptcha v2 - check captcha is completed before form submission

What is the best practice in checking a user has actually completed the captcha before form submission?

From the documentation I can see there is 2 callback functions data-callback and data-expired-callback.

The plan is to manipulate a boolean javascript variable setting to true/false on successful completion or on expiration and then check that the variable is true before form submission.

From a user perspective this will ensure that the user fills out the captcha before submission.

Malicious users could overwrite the javascript variable but the server side captcha validation will protect against this.

Upvotes: 0

Views: 2049

Answers (1)

Hearner
Hearner

Reputation: 2729

First in your form you have to put onsubmit="return check()". That means when you're submiting the form, before sending datas it will execute the function named check(). If the function returns false the form won't submit. It will look like this :

<form action="page.php" method="POST" name="form" onsubmit="return checkCaptcha ()">

Then you have your function :

<script language="javascript">
    function checkCaptcha ()
    {
        var captcha = document.getElementById('captcha ').value;

        if (captcha == "" || captcha == " ")
        {
            alert("please fill the captcha ");
            return false;
        }
        else
        if (captcha .length != 7)
        {
         return false 
        } // and so on
        else
        {
             // if everything is ok you can submit
            return true;
        }
    }
    </script>

Upvotes: 1

Related Questions