在屏幕上反应 reCaptcha 警报而不是错误消息

问题描述 投票:0回答:1

我在表单中遇到的问题是,当 reCaptcha 验证成功时,将显示警报消息,而不是任何空的或完整的输入字段的错误消息。控制台指示 reCaptcha 成功,但只要按下提交按钮,就会弹出警报。

import React, {useState, useRef, Suspense, lazy} from 'react'
import Stockpic from '../../media/stockpic.webp';
import ReCAPTCHA from "react-google-recaptcha";
import axios from 'axios';
import emailjs from 'emailjs-com';
import { useForm } from 'react-hook-form';

const Contact = () => {
  
  const [valid, setValid] = useState(false);
  const form = useRef();
  const [formErrors, setFormErrors] = useState({});

  const submitForm = (e) => {
    e.preventDefault();
    if (!form.current['message'].value.trim()) {
      setFormErrors({ ...formErrors, 'message': "Please enter a message" });
    } 
    if (!form.current['email'].value.trim()) {
      setFormErrors({ ...formErrors, 'email':"Please enter a valid email address"});
    } 
    if (!form.current["first-name"].value.trim()) {
      setFormErrors({ ...formErrors, 'first-name': "Please enter your first name"});
    } 
    if (!form.current["last-name"].value.trim()) {
      setFormErrors({ ...formErrors, 'last-name': "Please enter your last name"});
    } 
    setFormErrors(formErrors);
    if (!valid)
     {
      alert("Please verify you are not a robot")
    } else
    if (Object.keys(formErrors).length === 0) {
      emailjs.sendForm(`${process.env.REACT_APP_SERVICE_ID}`, `${process.env.REACT_APP_TEMPLATE_ID}`, form.current, `${process.env.REACT_APP_PUBLIC_KEY}`)
      form.current.reset();
      alert('Enquiry Sent!')
    }
  }

const captchaRef = useRef(null);

const reCaptchaValue = async () => {
  const token = captchaRef.current.getValue();
  console.log(token);
  await axios
    .post("http://localhost:4000/status", {
      response: token,
    })
    .then((res) => {
      console.log(res);
      setValid(res.data.success);
      if (!res.data) {
        alert("Please verify you are not a robot");
      }
    })
    .catch((err) => {
      console.log(err);
    });
};

  const {
    register,
    handleSubmit,
    formState: { errors }
  } = useForm({
    mode: "onChange"
  });

const LazyNav = lazy(() => import('../../Components/Navigation.jsx'))
const LazyFooter = lazy(() => import('../../Components/Footer.jsx'))

  return (
  <div>
    <Suspense fallback={<div />}>  
      <LazyNav/>
      </Suspense>
        <div>
          <div>
            Lorem ipsum dolor, sit amet consectetur adipisicing elit. Dolorum necessitatibus sunt, officia eveniet distinctio consequatur eius minima perspiciatis vel laborum assumenda magnam esse quae quas. Sint asperiores inventore eveniet iste!
          </div>
          <div>
            <img src={Stockpic} alt="" />
          </div>
            <form ref={form} onSubmit={handleSubmit(submitForm)}>
              <input className='contact-input' type='text' name='first-name' placeholder='Your First Name' required {...register("first-name", { required: true})} />
                {errors['first-name']  && <div className="text-red-600">{formErrors['first-name']}</div>}
              <input className='contact-input' type='text' name='last-name' placeholder='Your Last Name' required {...register("last-name", { required: true})} />
                {errors['last-name'] && <div className="text-red-600">{formErrors['last-name']}</div>}
              <input className='contact-input' type='email' name='email' placeholder='Your Email Address' 
              required {...register("email", {
                  required: true, 
                  pattern: {value: /^\S+@\S+$/i, }
                  })} 
                  />
                  {errors['email'] && <div className="text-red-600">{formErrors['email']}</div>}
              <textarea className='border-black border rounded-md block sm:w-1/2 mobile:w-5/6 tablet:w-full pl-2 resize-none hover:placeholder-gold placeholder:text-center mobile:text-base' name="message" rows="4" placeholder='Message' maxLength="6000" required></textarea>
                {errors['message'] && <div className="text-red-600">{formErrors['last-name']}</div>}
              <ReCAPTCHA 
              sitekey={`${process.env.REACT_APP_SITE_KEY}`}
              ref={captchaRef}
              onChange={() =>
              reCaptchaValue()}
              />
              <button onClick={submitForm} type="submit" href="#_">
                  <span className="relative">SEND</span>
              </button>
          </form>
        </div>
        <Suspense>
      <LazyFooter/>
    </Suspense>
  </div>
  )

  export default Contact

reactjs validation react-hooks recaptcha email-validation
1个回答
0
投票

这应该是用

valid
 更新 
res.data.success
状态的问题 如果
res.data.success
undefined
null
然后
if (!valid)
总是返回
true
所以警报无论如何都会弹出。
您应该根据条件将
valid
设置为
true
,因为在您的示例中,如果有响应,无论响应是什么,
valid
都会更新,所以您要做的是这样的:

.then((res) => {
   if (condition_that_makes_valid_true) {
     setValid(true);
   }else {
     alert("Please verify you are not a robot");
     setValid(false);
   }
})
© www.soinside.com 2019 - 2024. All rights reserved.