I was working on simple form Validation, when I press login button. It should check all the required field whether they are empty or not ? if yes then show the error message.
Below is the code snippet.
const [user, setUser] = useState({
name: "",
password: "",
email: "",
confirmpassword: "",
});
const [formErrors, setFormErrors] = useState({
name: "",
password: "",
email: "",
confirmpassword: "",
});
onSubmit:
const handleSubmit = (e) => {
e.preventDefault();
const isFormValid = validForm();
};
const validForm = () => {
if (
user.email.trim() === "" ||
user.password.trim() === "" ||
user.name.trim() === ""
) {
if (user.password.trim() === "") {
setFormErrors({
...formErrors,
password: "Password Length must be between 4 and 6 characters",
});
}
if (user.name.trim() === "") {
setFormErrors({ ...formErrors, name: "Required Field" });
}
if (user.email.trim() === "") {
setFormErrors({ ...formErrors, email: "Required Field" });
}
return false;
} else {
setFormErrors({ ...formErrors, email: "", password: "", name: "" });
return true;
}
};
{formErrors.email === "" ? null : (
<div className="">{formErrors.email}</div>
)}
Only email field is showing the required filled error, all are not getting updated.
Below is the snapshot of user object after clicking on login button.
{name: '', password: '', email: 'Required Field', confirmpassword: ''}
Please help on this.