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.
>Solution :
It is not working because you are trying to setState values same time, before updating so on the last line (email check) it will update the state with old values since none of the above setState is completed
I have a different method of implementation for validForm function
const validForm = () => {
let valid = true;
let tempFormErros = {}
if (user.password.trim() === "") { //&& add password condition check
tempFormErros.password = "Password Length must be between 4 and ...";
valid = false;
}
if (user.name.trim() === "") {
tempFormErros.name = "Required Field";
valid = false;
}
if (user.email.trim() === "") {
tempFormErros.email = "Required Field";
valid = false;
}
if(!valid) {
setFormErrors(tempFormErros)
}
return valid;
}
};