1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| import { useState } from "react" import "./App.css"
const InputItem = ({ handleInput, title, placeholder, error, isError }) => { return ( <> <p className="entry-name">{title}</p> <input className="input" type="text" placeholder={placeholder} onBlur={(e) => { handleInput(e.target.value, title) }} /> <p className="error">{isError && error}</p> </> ) }
export default function App() { const [username, setUsername] = useState("") const [email, setEmail] = useState("") const [password, setPassword] = useState("") const [confirm, setConfirm] = useState("")
const [usernameError, setUsernameError] = useState(false) const [emailError, setEmailError] = useState(false) const [passwordError, setPasswordError] = useState(false) const [confirmError, setConfirmError] = useState(false)
const handleInput = (value, title) => { if (title === "Username") { if (value && value.length >= 3) { setUsernameError(false) setUsername(value) } else setUsernameError(true) } else if (title === "Email") { const emailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/ if (value && emailReg.test(value)) { setEmailError(false) setEmail(value) } else setEmailError(true) } else if (title === "Password") { if (value && value.length >= 6) { setPasswordError(false) setPassword(value) } else setPasswordError(true) } else { if (value && value === password) setConfirmError(false) else { setConfirmError(true) setConfirm(true) } } } const handleClick = () => { if (username === "") setUsernameError(true) if (email === "") setEmailError(true) if (password === "") setPasswordError(true) if (confirm === "") setConfirmError(true)
if ( username !== "" && !usernameError && !emailError && !passwordError && !confirmError ) { alert("Register succeeded.") } }
return ( <div className="App"> <h2 className="title">Register With Us</h2> <InputItem handleInput={handleInput} title="Username" placeholder="Enter username" isError={usernameError} error="Username must be at least 3 characters" /> <InputItem handleInput={handleInput} title="Email" placeholder="Enter email" isError={emailError} error="Email is not valid" /> <InputItem handleInput={handleInput} title="Password" placeholder="Enter password" isError={passwordError} error="Password must be at least 6 characters" /> <InputItem handleInput={handleInput} title="Confirm Password" placeholder="Enter password again" isError={confirmError} error="Passwords are not the same" /> <button className="submit" onClick={handleClick}> Submit </button> </div> ) }
|