微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

更新 ReCaptcha 值以进行表单验证时如何保持状态?

如何解决更新 ReCaptcha 值以进行表单验证时如何保持状态?

我的目标是将 ReCaptcha 作为验证的一个步骤。在尝试实施 ReCaptcha 之前,Yup 的验证按预期工作。

我实现 ReCaptcha 的问题在于,每当用户提交 ReCaptcha 响应时,它都会清除表单值。

Example of Form Being Cleared on ReCaptcha Submit (控制台日志“false”在每次更改时更新 formValues.captcha)

我的目的是使用 setFormValues 函数将 formValues.captcha 状态从 false 更改为 true,就像这样。

setFormValues({...formValues,captcha:true})

这是下面的代码。我很乐意补充我所能提供的任何其他信息来解决此问题。

联系方式:

import axios from 'axios'
import * as Yup from 'yup'
import ReCAPTCHA from "react-recaptcha";

import Footer from '../footer'
import { useMediaQuery } from '../hooks/mediaQuery'
import Teamwork from '../../static/images/teamwork.jfif'
import contactUsSchema from '../validation/contactUsSchema'
import { Agent } from '../teamBio/agentInfo/agentInfoList'

import './style.css'

const testAPI = 'http://localhost:5000/api/send'

const initialValues = {
    intent: {
        buy: true,sell: false,lease: false,offerToLease: false,consult: false,},timeframe: {
        lessthan3: true,lessthan6: false,lessthan12: false,nextYear: false,agent: '',name: '',email: '',phone: '',message: '',captcha: false,}

const initialFormErrors = {
    intent: '',timeframe: '',captcha: '',}


export default function Contact() {
    // const [captchaValue,setCaptchaValue] = useState(false)
    const isHidden = useMediaQuery('(min-width: 1023px)');
    const [formValues,setFormValues] = useState(initialValues)
    const [formErrors,setFormErrors] = useState(initialFormErrors);
    const [disabled,setdisabled] = useState(true);

    // const [message,setMessage] = useState([]);

    //////////////// HELPERS ////////////////
    const postNewMessage = message => {
        axios.post(testAPI,message)
            .then(res => {
                if (res.data.status === 'success') {
                    alert('Message Sent.');
                }
                else if (res.data.status === 'fail') {
                    alert('Message Failed to send.')
                }
            })
            .catch(err => {
                console.log(err)
            })
            .finally(() => {
                setFormValues(initialValues)
            })
    }

    var verifyCallback = function(response) {
        console.log(formValues.captcha)
        console.log('response',response)
        setFormValues({...formValues,captcha:true})
    };

    //////////////// EVENT HANDLERS ////////////////
    
    const onInputChange = evt => {
        const { name,value } = evt.target
        Yup
            .reach(contactUsSchema,name)
            .validate(value)
            .then(valid => {
                setFormErrors({
                    ...formErrors,[name]: ""
                })
            })
            .catch(err => {
                setFormErrors({
                    ...formErrors,[name]: err.errors[0]
                })
            })
        setFormValues({
            ...formValues,[name]: value
        })
        console.log(formValues.captcha)
    }

    const onSubmitHandler = evt => {
        evt.preventDefault();
        const newMessage = {
            intent: formValues.intent,timeframe: formValues.timeframe,name: formValues.name.trim(),email: formValues.email.trim(),phone: formValues.phone.trim(),message: formValues.message.trim(),agent: formValues.agent
        };
        if(formValues.captcha === true){
            console.log('here is the message... ',newMessage)
            postNewMessage(newMessage);
        }
        else {alert('please complete the captcha')}
    }


    //////////////// SIDE EFFECTS //////////////// 
    useEffect(() => {
        contactUsSchema.isValid(formValues).then(valid => {
            setdisabled(!valid);
        })
    },[formValues])

    return (
        
        <div className="wrapper">
            
            <div className="flexColumn">
                <div className="content-row">
                    <form className="contact-us" onSubmit={onSubmitHandler}>
                        <label>I am looking to:</label>
                        <select
                            value={formValues.intent}
                            onChange={onInputChange}
                            name="intent"
                        >
                            <option value=''>Please select an option</option>
                            <option value="buy">Buy</option>
                            <option value="sell">Sell</option>
                            <option value="lease">Lease</option>
                            <option value="offerToLease">Offer to Lease</option>
                            <option value="consult">Consult/Other</option>
                        </select>

                        <label >My Timeframe is:</label>
                        <select
                            value={formValues.timeframe}
                            onChange={onInputChange}
                            name="timeframe"
                        >
                            <option value=''>Please select an option</option>
                            <option value="lessthan3">Less than 3 months</option>
                            <option value="lessthan6">Less than 6 months</option>
                            <option value="lessthan12">Less than 12 months</option>
                            <option value="nextYear">Next year</option>
                        </select>

                        <label> Agent:</label>
                        <select
                            value={formValues.agent}
                            onChange={onInputChange}
                            name='agent'
                        >
                            {/* <option value={Agent.JasonTest.email}>Jason Test</option> */}
                            <option value={Agent.MarkHughes.email}>Please select an agent</option>
                            <option value={Agent.AndreFournier.email}>Andre Forunier</option>
                            <option value={Agent.Libby.email}>Libby Brignon (Land)</option>
                            <option value={Agent.MarkHughes.email}>Mark Hughes (Team Lead | Generalist)</option>
                            <option value={Agent.SueNa.email}>Sue Na (Flex/Industrial | Multi Unit | Retail)</option>
                            <option value={Agent.TommyShort.email}>Tommy Short</option>
                            <option value={Agent.VanSpears.email}>Van Spears (Multi-Family | Industrial | Leasing | Investment)</option>
                            <option value={Agent.WillSchnieder.email}>Will Schnieder</option>

                        </select>


                        <label>Full Name</label>
                        <input
                            value={formValues.name}
                            onChange={onInputChange}
                            type='text'
                            placeholder='full name'
                            name='name'
                        />

                        <label>Email Address</label>
                        <input
                            value={formValues.email}
                            onChange={onInputChange}
                            type='email'
                            placeholder='email address'
                            name='email'
                        />

                        <label>Phone Number</label>
                        <input
                            value={formValues.phone}
                            onChange={onInputChange}
                            type='tel'
                            placeholder='phone'
                            name='phone'
                            maxLength='10'
                        />

                        <label> Message</label>
                        <textarea
                            value={formValues.message}
                            onChange={onInputChange}
                            type='text'
                            className="message-Box"
                            placeholder='type your message here'
                            name="message"
                        />
                        <ReCAPTCHA
                            sitekey="~ ~ ~ R E D A C T E D ~ ~ ~"
                            verifyCallback = {verifyCallback}
                        />
                        <button disabled={disabled} onSubmit={onSubmitHandler}>Send</button>

                    </form>
                    <img style={styles.container(isHidden)} id="teamworkimg" alt="generic team working together" src={Teamwork} />
                </div>
            </div>


            <Footer />
        </div>
    )
}

const styles = {
    container: isHidden => ({
        display: isHidden ? 'flex' : 'none',})
};

验证架构:

import * as Yup from "yup";
import { Agent } from '../teamBio/agentInfo/agentInfoList'

const phoneRegExp = /^((\\+[1-9]{1,4}[ \\-]*)|(\\([0-9]{2,3}\\)[ \\-]*)|([0-9]{2,4})[ \\-]*)*?[0-9]{3,4}?[ \\-]*[0-9]{3,4}?$/

const contactUsSchema = Yup.object().shape({
    name: Yup
        .string()
        .min(3,"Name must be at least 3 characters long.")
        .required("Name is required"),email: Yup
        .string()
        .email("Must be a valid email address.")
        .required("Must include email address."),phone: Yup
        .string()
        .matches(phoneRegExp,'Phone number is not valid')
        .max(10,'Please double check your phone number')
        .min(10,"Phone number must include area code.")
        .required("Phone number is required"),intent: Yup
        .string()
        .oneOf(['buy','sell','lease','offerToLease','consult'])
        .required("intent is required"),timeframe: Yup
        .string()
        .oneOf(['lessthan3','lessthan6','lessthan12','nextYear'])
        .required("timeframe is required"),agent: Yup
        .string()
        .oneOf([Agent.AndreFournier.email,Agent.MarkHughes.email,Agent.Libby.email,Agent.SueNa.email,Agent.JasonTest.email,Agent.TommyShort.email,Agent.VanSpears.email,Agent.WillSchnieder.email,Agent.Antonia.email,'NA']),message: Yup
        .string(),captcha: Yup
        .boolean()
        .oneOf([true])
        .required()

})

export default contactUsSchema

这是我的第一篇 stackoverflow 帖子,请多多关照,谢谢大家的见解。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?