Google reCaptcha v2 - 检查验证码是在表单提交之前完成的

时间:2015-07-24 10:34:41

标签: javascript html forms recaptcha

在表单提交之前检查用户是否已实际完成验证码的最佳做法是什么?

从文档中我可以看到有2个回调函数data-callback和data-expired-callback。

计划是在成功完成或到期时将布尔javascript变量设置为true / false,然后在表单提交之前检查变量是否为真。

从用户角度来看,这将确保用户在提交前填写验证码。

恶意用户可能会覆盖javascript变量,但服务器端验证码验证会阻止此操作。

1 个答案:

答案 0 :(得分:1)

首先在form中,您必须放置onsubmit="return check()"。这意味着当您提交表单时,在发送数据之前,它将执行名为check()的函数。如果函数返回false,则表单将不会提交。它看起来像这样:

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

然后你有你的功能:

<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>
相关问题