如何检入 js,用户已经选中了复选框在谷歌重演?

我已经添加了以下头前结束

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

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

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

我能看到类似于 https://developers.google.com/recaptcha/的重演

但是,当用户没有选中复选框就按下数据时,数据就被提交了。是否需要添加其他代码来检查用户是否已经按了复选框?希望是在 JS?

101979 次浏览

Google has a call back option for when the checkbox is checked.

Add this to your form element:

data-callback="XXX"

Example:

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

And a disable attribute to your submit button.

Example:

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

Then a create a callback function and write whatever code you need.

Example:

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

You can also call the grecaptcha object to check. grecaptcha.getResponse(); is empty when unchecked and has the verification code when checked.

grecaptcha.getResponse().length === 0 when unchecked

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


if (isCaptchaChecked()) {
// ...
}

Let the browser do the job for you! (based on slinky2000 answer)

note: this is only to prevent sending an 'accidentally' unchecked recaptcha. You still have to verify the recaptcha on server side because a bot does not care ...

Add a an invisible input tag with required=true attribute just below the div.g-recaptcha.

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

Enclose both width a div with position=relative; to point the bottom:0; above to the bottom of recaptcha.

Now the Browser asks nicely to fill out this field - pointing to the recapcha.

Now we need the callback:

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

and

function recaptchaCallback() {
$('#recaptcha_check_empty').val(1);
}

To check if google recaptcha is checked or not you can do it by the following code :

<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>

To check if google recaptcha v2 is checked or not you can do it by the following code :

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
}
});
})
<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>

if for some reason you are conditioning a form by hand like me, and required is not working.

First import ReCAPTCHA

import  ReCAPTCHA  from 'react-google-recaptcha'

Apply it in your component

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

you can use a useRef or just use the ReCAPTCHA you've imported, I used useRef.

const recaptchaRef = useRef<any>()

And now, how do I check if recaptchaRef is checked?

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

basically, you are saying 'if recaptcha is true, then do this'

this is complete form code that helps you (I'm using 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)
}