即使驗證要求無效,數據仍在發送,解決此問題的最佳方法是什麼? (Data is sending even if validation requirements are not valid, whats the best way to approach this?)


問題描述

即使驗證要求無效,數據仍在發送,解決此問題的最佳方法是什麼? (Data is sending even if validation requirements are not valid, whats the best way to approach this?)

所以我設置了一個帶有簡單驗證的自定義反應鉤子表單(驗證有效),表單中的數據發送到我的 Gmail,但即使字段為空,我也會在按鈕提交時收到電子郵件,我'已經嘗試了一些方法來解決這個問題,但似乎沒有任何效果,代碼如下所示:

Form.js :

import React from "react";
import useForm from "./useForm";
import validate from "./validate";

const Form = () => {
const { handleChange, handleSubmit, values, errors } = useForm(
submit,
validate
);

function submit() {
    alert("Submitted Succesfully");
}

return (
    <div>

        <form onSubmit={handleSubmit} noValidate>
            <div className="inputField">
                <input className={`${errors.email && "inputError"}`} name="email" type="email" placeholder="Your email *" value={values.email} onChange={handleChange} />
                {errors.email && <p className="error">{errors.email}</p>}
            </div>
            <div className="inputField">
                <input className={`${errors.email && "inputError"}`} name="name" type="text" placeholder="Your name *" value={values.name} onChange={handleChange} />
                {errors.email && <p className="error">{errors.name}</p>}
            </div>
            <div className="inputField">
                <input className={`${errors.email && "inputError"}`} name="subject" type="text" placeholder="Subject *" value={values.subject} onChange={handleChange} />
                {errors.email && <p className="error">{errors.subject}</p>}
            </div>
            <div className="inputField">
                <p className="reqTxt"> * = Required</p>
                <textarea className={`${errors.email && "inputError"}`} name="description" placeholder="Type your message here *" value={values.description} onChange={handleChange} rows="15" cols="80"></textarea>
                {errors.email && <p className="error">{errors.description}</p>}
            </div>


            <button className="btn" type="submit">Send message</button>
        </form>
    </div>
);

};
</code></pre>

useForm.js :

import { useState, useEffect } from "react";
import axios from 'axios';

const useForm = (callback, validate) => {
const [values, setValues] = useState({ email: '', name: '', subject: '', description: '' })
const [errors, setErrors] = useState({});
const [isSubmitting, setIsSubmitting] = useState(false);

const handleChange = event => {
const { name, value } = event.target;
setValues({
...values,

  [name]: value
});

};

const handleSubmit = (event) => {
event.preventDefault();
setErrors(validate(values));
setIsSubmitting(true);

const {email,name,subject,description} = values;

axios.post('http://localhost:8080/sendme', {

        email,
        name,
        subject,
        text: description
    })

};

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

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

export default useForm;
</code></pre>

validate.js :

</blockquote >
export default function validate(values) {
    let errors = {};
    if (!values.email) {
        errors.email = "Email is required";
    } else if (!/\S+@\S+\.\S+/.test(values.email)) {
        errors.email = "Email address is invalid, ex: your@email.com";
    }
    if (!values.name) {
        errors.name = "Please type in your name.";
    }
    if (!values.subject) {
        errors.subject = "Please don't leave the subject field empty.";
    }
    if (values.description.length < 20) {
        errors.description = "Your message needs to be more than 20 characters.";
    }
    return errors;
}

解決這個問題的最佳方法是什麼(僅在表單驗證 = true 或其他內容後發送數據)?我也想知道如何顯示“成功”。


參考解法

方法 1:

In useForm hook (handleSubmit method) you don't stop the method if there are any errors. You should return from the function if there are errors.

Something like

const handleSubmit = (event) => {
    event.preventDefault();

    const errors = validate(values);

    if (Object.keys(errors).length > 0) {
       setErrors(errors);
       return;
    }

    setIsSubmitting(true);

    const {email,name,subject,description} = values;

    axios.post('http://localhost:8080/sendme', {

            email,
            name,
            subject,
            text: description
        })
  };

(by andrPauRosen Dimov)

參考文件

  1. Data is sending even if validation requirements are not valid, whats the best way to approach this? (CC BY‑SA 2.5/3.0/4.0)

#react-hooks #Axios #javascript #reactjs #validation






相關問題

使用反應鉤子useState更新功能的正確方法是什麼? (What is the correct way to use react hook useState update function?)

測試 react-redux useSelector (testing react-redux useSelector)

從深度嵌套的組件更新狀態而不重新渲染父組件 (Update state from deeply nested component without re-rendering parents)

React Hook useEffect 缺少依賴項(在上下文中定義的函數) (React Hook useEffect has a missing dependency (function defined in context))

類型“IntrinsicAttributes”(自定義掛鉤)上不存在 React 屬性 (React Property does not exist on type 'IntrinsicAttributes' (custom hook))

即使驗證要求無效,數據仍在發送,解決此問題的最佳方法是什麼? (Data is sending even if validation requirements are not valid, whats the best way to approach this?)

如何在使用狀態掛鉤更新狀態時覆蓋具有相同鍵的對象 (How can overwrite objects that have the same key in updating State with state hooks)

在 useEffect 中,調用更新時是否會更新所有變量? (In useEffect, do all variables get updated when an update is called?)

反應鉤子,不會將選中的屬性更改為複選框 (React hooks, does not change the checked property to checkbox)

在 reactJS 中動態設置圖像 src (Setting image src dynamically in reactJS)

如何防止組件在反應中重新渲染? (How to prevent component from re-rendering in react?)

使用 useEffect 和 setInterval 一個接一個地打印一個字母 (print one letter after the other with useEffect and setInterval)







留言討論