i have error
state object to validate form inputs :
const [error, setError] = useState({
nameArErr: "",
nameEnErr: "",
accountNumberErr: "",
ageErr: "",
phoneNumberErr: "",
hireDateErr: "",
birthDateErr: "",
});
const handleAdd = (e) => {
setError({});
if (nameAr.current.value.length < 11) {
setError({ ...error, nameArErr: "please enter your full name" });
}
if (nameEn.current.value.length < 11) {
setError({ ...error, nameEnErr: "please enter your full name" });
}
if (accountNumber.current.value === "") {
setError({ ...error, accountNumberErr: "account number can't be empty" });
}
if (
Number(age.current.value) > 60 ||
Number(age.current.value) < 18 ||
age.current.value === ""
) {
setError({ ...error, ageErr: "please enter a valid age" });
}
if (phoneNumber.current.value.length !== 10) {
setError({
...error,
phoneNumberErr: "please enter a valid phone number",
});
}
if (hireDate.current.value === "") {
setError({ ...error, hireDateErr: "hire date can't be empty" });
}
if (birthDate.current.value === "") {
setError({ ...error, birthDateErr: "birth date can't be empty" });
}
console.log(error);
};
my problem with code is :
first if all if statements
are true it will not setState
all at once it will rather setState
of the last true if statement
second setError({});
works only if all statements
are wrong, but what i want is let's say the function is triggered and the first if statement
applies then nameArErr
value would be "please enter your full name"
, then suppose the function is triggered again and the statement doesn't apply anymore, then nameArErr
should be empty by this line of code setError({});
but it doesn't until all statements are wrong!
CodePudding user response:
I would use an array/object to store the errors and at the end a setState with the array/object (or nothing if there is no error):
const [error, setError] = useState({});
const handleAdd = (e) => {
let errors = {};
if (nameAr.current.value.length < 11) {
errors.nameArErr = "please enter your full name";
}
if (nameEn.current.value.length < 11) {
errors.nameEnErr= "please enter your full name";
}
if (accountNumber.current.value === "") {
errors.accountNumberErr = "account number can't be empty";
}
if (
Number(age.current.value) > 60 ||
Number(age.current.value) < 18 ||
age.current.value === ""
) {
errors.ageErr = "please enter a valid age";
}
if (phoneNumber.current.value.length !== 10) {
errors.phoneNumberErr = "please enter a valid phone number";
}
if (hireDate.current.value === "") {
errors.hireDateErr = "hire date can't be empty";
}
if (birthDate.current.value === "") {
errors.birthDateErr = "birth date can't be empty";
}
setError(errors);
};