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