首页 > 解决方案 > 我正在尝试为表单验证创建一个自定义挂钩

问题描述

我是一名 React 初学者,一直在尝试为我的联系表单制作一个自定义错误处理程序挂钩。我已经完成了我所知道的一切,但我无法让它触发提交消息或错误消息。我不确定UseForm.tsx中的回调和验证应该是什么类型,也不知道ValidateLogin接口是否正确。

这是我的代码:

使用Form.tsx:

import React, {useState, useEffect} from "react";



const UseForm = (callback:any, validate:any) => {
    const [contact, setContact] = useState({
        name: "",
        email: "",
        title: "",
        content: ""
    });
    const [errors, setErrors] = useState({
        name: "",
        email: "",
        title: "",
        content: ""
    });
    const [isSubmitting, setIsSubmitting] = useState(false);

    function handleChange(e: React.ChangeEvent<HTMLInputElement> | React.ChangeEvent<HTMLTextAreaElement>) {
        const {name, value} = e.target
        setContact({...contact, [name]: value})
    }


    const handleSubmit = (e:React.ChangeEvent<HTMLFormElement>) => {
        e.preventDefault();
        setErrors(validate(contact));
        setIsSubmitting(true);
    };

    useEffect(() => {
        if (Object.keys(errors).length === 0 && isSubmitting) {
            callback();
        }
    }, [errors]);

    return {
        handleChange,
        handleSubmit,
        contact,
        errors
    };
};

export default UseForm

验证登录.tsx:


interface Contact {
    email: string;
    name: string
    title:string
    content:string
}

type Error = Partial<Contact>

const ValidateLogin = (contact: Contact) => {
    let errors: Error= {};
    if (!contact.email) {
    } else if (!/\S+@\S+\.\S+/.test(contact.email)) {
        errors.email = "Email address is invalid";
    }
    if (!contact.name) {
        errors.name = "Name is required";
    }
    if (!contact.title) {
        errors.title = "Title is required";
    }
    if (!contact.content) {
        errors.content = "Content is required";
    }
    return errors;
}

export default ValidateLogin

联系方式.tsx:

import React from "react";
import {useStep} from "react-hooks-helper";
import useForm from "../components/UseForm"
import validate from "../components/ValidateLogin";


const Contact: React.FC = () => {

    const {handleChange, handleSubmit, contact, errors} = useForm(
        submit,
        validate
    );

    function submit() {
        console.log("Submitted Succesfully");
    }

    const {index, navigation: {previous, next},} = useStep({steps: 4});


    return (

        <div className="contact">
            <div className="contact-inner">
                <form onSubmit={handleSubmit} noValidate>
                    {index === 0 && <label>
                        <input onChange={handleChange} value={contact.name} type="text" name="name"
                               placeholder="Please enter your name"/>
                        {!errors.name && <p className="error">{errors.name}</p>}
                    </label>}
                    {index === 1 && <label htmlFor="email">
                        <input onChange={handleChange} value={contact.email} type="email" name="email"
                               placeholder="Please enter your email"/>
                        {errors.email && <p className="error">{errors.email}</p>}
                    </label>}
                    {index === 2 && <label>
                        <input onChange={handleChange} value={contact.title} type="text" name="title"
                               placeholder="Please enter the title"/>
                        {errors.title && <p className="error">{errors.title}</p>}
                    </label>}
                    {index === 3 && <label>
                        <textarea onChange={handleChange} value={contact.content} className="content" name="content"
                                  placeholder="Please enter your message"/>
                        {errors.content && <p className="error">{errors.content}</p>}
                    </label>}
                </form>
                <div className="buttons">
                    {index === 0 ? <button onClick={previous} disabled>Previous</button> :
                        <button onClick={previous}>Previous</button>}
                    {index === 3 ? <button type="submit">Submit</button> : <button onClick={next}>Next</button>}

                </div>
            </div>
        </div>
    )
}

export default Contact

标签: reactjstypescriptreact-hooksreact-typescript

解决方案


推荐阅读