如何在js中签入用户已选中Google验证码中的复选框

How to check in js that user has checked the checkbox in Google recaptcha?

本文关键字:验证 Google 复选框 用户 js      更新时间:2024-03-17

我在头尾之前添加了以下内容

<script src='https://www.google.com/recaptcha/api.js'></script>

我已经在表格结束之前添加了这个

<div class="g-recaptcha" data-sitekey="== xxxxxx =="></div>

我可以看到类似于 https://developers.google.com/recaptcha/的验证码

每当用户按下数据而不选中复选框时,将提交数据。我是否需要添加任何其他代码来检查用户是否已按下复选框?希望在 js 中?

Google有一个回调选项,用于选中该复选框。

将其添加到表单元素中:

data-callback="XXX"

例:

<div class="g-recaptcha" data-callback="recaptchaCallback" data-sitekey="== xxxxxx =="></div>

以及提交按钮的禁用属性。

例:

<button id="submitBtn" disabled>Submit</button>

然后创建一个回调函数并编写您需要的任何代码。

例:

function recaptchaCallback() {
    $('#submitBtn').removeAttr('disabled');
};

您也可以调用 grecaptcha 对象进行检查。 grecaptcha.getResponse();在未选中时为空,在选中时具有验证码。

未选中时grecaptcha.getResponse().length === 0

function isCaptchaChecked() {
  return grecaptcha && grecaptcha.getResponse().length !== 0;
}
if (isCaptchaChecked()) {
  // ...
}

要检查是否检查了谷歌验证码,您可以通过以下代码进行操作:

<script>
if(grecaptcha && grecaptcha.getResponse().length > 0)
{
     //the recaptcha is checked
     // Do what you want here
     alert('Well, recaptcha is checked !');
}
else
{
    //The recaptcha is not cheched
    //You can display an error message here
    alert('Oops, you have to check the recaptcha !');
}
</script>

要检查是否检查了谷歌验证码v2,您可以通过以下代码进行操作:

var checkCaptch = false;
     var verifyCallback = function(response) {
        if (response == "") {
             checkCaptch = false;
         }
         else {
             checkCaptch = true;
         }
     };
     $(document).ready(function() {
         $("#btnSubmit").click(function() {
             if (checkCaptch && grecaptcha.getResponse()!="") {
                  //Write your success code here
             }
         });
     })

让浏览器为您完成这项工作!(基于 Slinky2000 答案(

注意:这只是为了防止发送"意外"未经检查的验证码。您仍然必须在服务器端验证验证码,因为机器人不在乎......

div.g-recaptcha 下方添加一个不可见的输入标签required=true属性。

<input id='recaptcha_check_empty' required tabindex='-1',
style='width:50px; height:0; opacity:0; pointer-events:none; 
position:absolute; 
bottom:0;'>

position=relative;将两个宽度都括起来div,将上面的bottom:0;指向验证码的底部。

现在浏览器很好地要求填写此字段 - 指向 recapcha。

现在我们需要回调:

<div class="g-recaptcha" data-callback="recaptchaCallback" ...

function recaptchaCallback() { 
    $('#recaptcha_check_empty').val(1);
}
<div class="contact-inner contact-message">
  <label for="message-text" class="col-form-label">CAPTCHA</label>
  <div class="g-recaptcha" data-sitekey="<?php echo 6LfSJmocAAAAAFFMpMKB1CtYNJYDyDswO7GpxRXS ;?>">
  </div>
</div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src='https://www.google.com/recaptcha/api.js'></script>
<!DOCTYPE html>
<html>
  <head>
    <title>CAPTCHA</title>
  </head>
  <body>
      <div class="contact-inner contact-message">
        <label for="message-text" class="col-form-label">CAPTCHA</label>
        <div class="g-recaptcha" data-sitekey="<?php echo GOOGLE_KEY ;?>"></div>
      </div>
  </body>
</html>

如果由于某种原因您像我一样手动调节表单,并且必需不起作用。

首次导入验证码

import  ReCAPTCHA  from 'react-google-recaptcha'

将其应用于组件中

<ReCAPTCHA style={{margin: '5px', transform: 'scale(0.8)'}} ref={recaptchaRef} sitekey={recaptchaKey} onChange={updateRecaptcha}/>

您可以使用useRef或仅使用导入的ReCAPTCHA,我使用了useRef.

const recaptchaRef = useRef<any>()

现在,如何检查是否检查recaptchaRef

if (recaptchaRef.current.props.grecaptcha.getResponse().length !== 0) {
    //your condition
}

基本上,您是在说"如果验证码是真的,那就这样做">

这是帮助您的完整表单代码(我正在使用typeScipt(

const Formid = // yout formid
const FormSpark = `https://submit-form.com/${Formid}`
type FormState =  {
    name: string,
    mail: string,
    message: string
}
const initialState = {
    name: '',
    mail: '',
    message: '',
}
const [wrongmail, setWrongmail] = useState(false)
const [wrongname, setWronname] = useState(false)
const [wrongtext, setWrongtext] = useState(false)
const [alert, setAlert] = useState(false)
const recaptchaRef = useRef<any>()
const recaptchaKey = //your recaptcha public key    const [recaptchaToken, setRecaptchaToken] = useState<string>()
const [formstate, setFormState] = useState<FormState>(initialState)
const submit = async(event: FormEvent) =>{
    event.preventDefault()
    await postSubmission()
}
const updateRecaptcha = (token: string | null)=>{
    setRecaptchaToken(token as string)
}
const {name, mail, message} = formstate
const postSubmission = async() => {
    const payload = {
        ...formstate,
        "g-recaptcha-response": recaptchaToken
    }
    try {
        if (name && mail && message) {
            if (mail.includes('@') && mail.includes('.') && mail.length > 5) {
                if (name.includes(' ') && name.length> 5) {
                    if (message.length > 20) {
                        if (recaptchaRef.current) {
                            if (recaptchaRef.current.props.grecaptcha.getResponse().length !== 0) {
                                console.log('hola')
                                setAlert(true)
                                const result = await axios.post(FormSpark, payload)
                                setFormState(initialState)
                                recaptchaRef.current.reset()
                                if (result) {
                                    setTimeout(() => {
                                        setAlert(false)
                                    },2000)
                                }
                            }
                        }
                    }
                }
            }
            if (!name && !(name.length> 5) && !(name.includes(' '))) {
                setWronname(true)
                setTimeout(() => {
                    setWronname(false)
                },3000)
            }
            if (!mail && !mail.includes('@') && !mail.includes('.') && !(mail.length > 5)) {
                setWrongmail(true)
                setTimeout(()=>{
                    setWrongmail(false)
                },3000)
            }
            if (!message && !(message.length > 20)) {
                setWrongtext(true)
                setTimeout(() => {
                    setWrongtext(false)
                },3000)
            }
        }
    } catch(error){
        console.log(error);
    }
}
const updateForm = (event: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const {id, value} = event.target
    const formKey = id as keyof FormState
    const updatedFormState = {...formstate}
    updatedFormState[formKey] = value
    setFormState(updatedFormState)
}