일부 순풍과 함께 UseHooks 및 LocalStorage를 사용하는 React의 간단한 유효성 검사 양식🥳🎉

5462 단어
내 블로그에 오신 여러분 안녕하세요. 정말 감사드리며 간단한 확인 등록 양식을 만드는 데 도움이 되었으면 합니다.🙏🙏

긴 블로그를 작성하고 싶지 않으니 코드 속으로 들어가 봅시다. 👨‍💻 👩‍💻

First Let's Write Simple jsx code:



<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}

        <label htmlFor="email">Email:</label>
        <input
          type="email"
          placeholder="email address"
          id="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />
        {errors.email}

        <label htmlFor="password">Password:</label>
        <input
          type="text"
          placeholder="password"
          value={password}
          id="password"
          onChange={(e) => setPassword(e.target.value)}
        />
        {errors.password}

        <label htmlFor="phoneNumber">phone Number:</label>
        <input
          type="text"
          value={phoneNumber}
          placeholder="phone Number"
          id="phoneNumber"
          onChange={(e) => setPhoneNumber(e.target.value)}
        />

        <div className="buttons flex gap-3 justify-center mt-5">
          <button type="submit" className="btn-1">
            Sign Up
          </button>
          <button>
            <Link
              className="
        "
              to="/login"
            >
             Login{" "}
            </Link>
          </button>
        </div>
      </form>
    </div>



2- 이 양식을 동적으로 만들 시간입니다.
사용하는 UseState 후크를 먼저 시작해야 합니다.

 const [email, setEmail] = useState("")
         const [password, setPassword] = useState("")
         const [name, setName] = useState("")
         const [phoneNumber, setPhoneNumber] = useState("")
         const [errors, setErrors] = useState({})


Prepare the Submit Button As Like that



const handleSubmit = (e) => {
    e.preventDefault()
    formValidation()
    setUsers([...users, { email: email, password: password }])
  }


And Now It's Time To Hit Some Conditions for the Right Register



 const formValidation = () => {
    let newErrors = {}
    if (name === "") {
      newErrors.name = <h1 className="text-red-800 text-center">
        Name Can't Be Blanck</h1>
    }
    if (email === "") {span
      newErrors.email = <span className="text-red-800 text-center">
         Email Address Is Required</span>
    } else if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {
      newErrors.email = <span className="text-red-800 text-center">
        Email address is invalid</span>
    } else {
      newErrors.email = <h1 className="text-green-800 text-center ">
        Email is Valid</h1>
    }
    if (password === "") {
      newErrors.password = <span className="text-red-800 text-center">
        Password Is Required</span>
    } else if (!/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15}$/.test(password)) {
      newErrors.password = <span className="text-red-800 text-center">
        Invalid Password Format</span>
    } else {
      newErrors.password = <span className="text-green-800 text-center ">
        Correct Password</span>
    }
    setErrors(newErrors)
  }


> 그리고 마지막 단계는 다음과 같은 방식으로 사용자 데이터를 localstorage에 저장하는 것입니다.



We can initiate the localstorage



const [users, setUsers] = useState(() => {
    const data = localStorage.getItem("data")
    return data ? JSON.parse(data) : []
  })


And Using UseHooks to Watch if there is not a user in localstorage before to set a new one



useEffect(() => {
    localStorage.setItem("data", JSON.stringify(users))
  }, [users])



👉 Visit my github account

> 결론:



In the end, I tried to write a simple validation form to learn how to use usehooks and also save it in localstorage. I hope that I was able to help you, and good luck always

좋은 웹페이지 즐겨찾기