After submission if there are any error, on user inputfield typing wants to remove that error. My Approach.
const validateField = (field, value) => {
if (!value.trim()) {
return "This field is required";
}
const regexRules = {
name: /^[A-Za-z ]+$/,
email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/
};
if (regexRules[field] && !regexRules[field].test(value)) {
return "Invalid format";
}
return "";
};
const handleChange = (e) => {
const { name, value } = e.target;
setForm((prev) => ({ ...prev, [name]: value }));
setErrors((prev) => ({ ...prev, [name]: "" }));
};
const handleSubmit = () => {
const newErrors = {};
Object.keys(form).forEach((field) => {
newErrors[field] = validateField(field, form[field]);
});
setErrors(newErrors);
const isValid = Object.values(newErrors).every((err) => err === "");
// submit flow
};
<input
name="name"
value={form.name}
onChange={handleChange}
/>
{errors.name && <p>{errors.name}</p>}
removing the error onChange because found it more controlled manner. In my seniors adviced approach:
const handleChange = (e) => {
const { name, value } = e.target;
setForm((prev) => ({ ...prev, [name]: value }));
};
const handleSubmit = () => {
const newErrors = {};
Object.keys(form).forEach((field) => {
newErrors[field] = validateField(field, form[field]);
});
setErrors(newErrors);
// submit flow
};
<input
name="name"
value={form.name}
onChange={handleChange}
/>
{!form.name && errors.name.required && (
<p>This field is required</p>
)}
{form.name && errors.name.regexFail && (
<p>Invalid format</p>
)}
In their approach to remove the error on user type do not render that error message below the input field. where i though error can be managed on single error key state.
please review which approach should be used.