My fields in the form require that I focus on them for the error messages to appear. I want the error messages to occur when I click on submit when I haven't focused the fields yet.
Here's the hook (the doubt is about the setIsTouched call later):
const useInputModifed = (validationArray) => {
const [enteredValue, setEnteredValue] = useState("");
const [isTouched, setIsTouched] = useState(false);
// [{errorName:,fn:validationFn}]
let errorArray = [];
for (const errorEntry of validationArray) {
if (errorEntry.isErrorFn(enteredValue)) {
errorArray.push(errorEntry.errorName);
}
}
const hasError = errorArray.length > 0 && isTouched;
const valueChangeHandler = (event) => {
setEnteredValue(event.target.value);
};
const reset = () => {
setEnteredValue("");
setIsTouched(false);
};
console.log(errorArray, isTouched);
return {
value: enteredValue,
validationArray: errorArray,
hasError,
valueChangeHandler,
setIsTouched,
isTouched,
reset,
};
};
Here's the form handler (I have used aliases for each field):
const formSubmissionHandler = (event) => {
event.preventDefault();
touchNameField(true);
touchEmailField(true);
if (nameInputHasError || emailInputHasError) {
//console logging both fields gives false even after touching
return;
}
if (!nameInputHasError && !emailInputHasError) {
resetNameInput();
resetEmailInput();
}
};
Take the validation that the name field is empty for example and I click the submit button in the beginning itself.
Currently in const hasError = errorArray.length > 0 && isTouched;
the array has elements but isTouched is false, as I did not focus the field.
So then the `touchNameField(true);' comes in. I try to make hasError true, but it's still showing false.
Is the fact that setState calls are asynchronous the issue? If I remove the reset calls it works. But I still don't understand why the nameInputError etc are false.