开发者问题收集

页面加载时如何防止使用效应显示验证错误?

2022-08-01
40

const Login = () => {

const [errors, setErrors] = useState({})

var newErrors = {

const formValidation = () => { if (name === "") { newErrors.name = 名称不能为空白

if (email === "") {
  newErrors.email = <h1 className="text-red-800 text-center"> Email Address Is Required</h1>
} else if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {
  newErrors.email = <h1 className="text-red-800 text-center">Email address is invalid</h1>
} else {
  newErrors.email = <h1 className="text-green-800 text-center ">Email is Valid</h1>
}

if (password === "") {
  newErrors.password = <h1 className="text-red-800 text-center">Password Is Required</h1>
} else if (!/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15}$/.test(password)) {
  newErrors.password = <h1 className="text-red-800 text-center">Invalid Password Format</h1>
} else {
  newErrors.password = <h1 className="text-green-800 text-center ">Correct Password</h1>
}

setErrors(newErrors)

>

const handleSubmit = (e) => { e.preventDefault()

formValidation()
console.log({ name, email, password })

>

useEffect(() => { if (newErrors) { formValidation() 在此处输入代码 } }, [name, email, password])

return (
<div
  className="login grid place-content-center  
bg-gradient-to-r from-purple-900 via-purple-1000 to-blue-800 "
>
  <form
    className="card grid place-content-center  h-96 w-96  
   "
    onSubmit={handleSubmit}
  >
    <label htmlFor="">name:</label>
    <input
      type="text"
      value={name}
      placeholder="Enter Your Name"
      onChange={(e) => setName(e.target.value)}
    />
    {errors.name}
  </form>
</div>

)

导出默认登录

1个回答

我的做法是添加一个名为 loading 的状态 const {loading,setLoading}= useState(false) 当然,在 loading 时将 loading 设置为 true。 并使用 { loading? null : errors.name } 有条件地呈现错误。

Alaa Eddine Cherif
2022-08-01