Today we’re going to learn how we can validate a form, including a reCAPTCHA to prevent spam attacks by BOTS.
![](https://i0.wp.com/images.pexels.com/photos/164425/pexels-photo-164425.jpeg?w=1200&ssl=1)
The first thing we need to do is register our reCAPTCHA code on Google: https://www.google.com/recaptcha/about/
And click on v3 Admin Console
![](https://i0.wp.com/devcodelight.com/wp-content/uploads/2024/04/imagen-13.png?resize=216%2C58&ssl=1)
Click on the plus (+) button to create a new one, and in this case, we’ll choose V2 invisible:
![](https://i0.wp.com/devcodelight.com/wp-content/uploads/2024/04/imagen-14.png?resize=883%2C583&ssl=1)
Google has a technique to verify invisible captcha using mouse movements.
We add the domains where the reCAPTCHA will work.
Once registered, copy the key and paste it into a file named GoogleUtils.tsx
export const GoogleReCaptchaSiteKey = "fsadfasdcdsafretrefrewf"
*Put your key.
Now install the library we’ll use to generate this reCAPTCHA, react-google-recaptcha
npm install --save react-google-recaptcha
And if we’re using TypeScript, add
npm i --save-dev @types/react-google-recaptcha
Now create a component named Captcha.tsx
import React from 'react'; import ReCAPTCHA from "react-google-recaptcha"; import { GoogleReCaptchaSiteKey } from '@/util/BaseURL'; interface Props { captchaRef: any; onChange?: (token: string null) => void; } function Captcha({ captchaRef, onChange }: Props) { return ( <ReCAPTCHA sitekey={GoogleReCaptchaSiteKey} size="invisible" ref={captchaRef} onChange={onChange} /> ); } export default Captcha;
And call it like this:
- Create the necessary methods to execute:
const captchaRef = useRef<any>(null); const [tokenCaptcha, setTokenCaptcha] = useState<string null>(null); //To login useEffect(() => { alert('TOKEN Captcha: ' + tokenCaptcha); //login(); }, [tokenCaptcha]) function checkCaptcha() { captchaRef.current.execute(); }
- Add the captcha to the form:
<CaptchaRecaptcha captchaRef={captchaRef} onChange={(token) => { setTokenCaptcha(token) }} />
And in the button, add the checkCaptcha function instead of submitting the form:
<pre class=”EnlighterJSRAW” data-enlighter-language=”generic” data-enlighter-theme=”” data-enlighter-highlight=”” data-enlighter-linenumbers=”” data-enlighter-lineoffset=”” data-enlighter-title=”” data
![](https://i0.wp.com/devcodelight.com/wp-content/uploads/2023/07/cropped-light_logo-5.png?resize=100%2C100&ssl=1)