i'm building a form in Preact and struggle to validate the inputs on form submit.
The <TextInput>
Component gets passed a validation object from validate.js
and handle the validation on it's own.
The parent Component is a form that stores the data in a formData
state and submits the values to an API.
Before submitting i want to validate the data again to prevent the user skipping some required inputs.
Question: What's the "react-way" to solve this problem?
Input:
export default function TextInput({ onChange, validation }) {
const [value, setValue] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
onChange && onChange(value);
}, [value]);
const handleBlur = (e) => {
const value = e.currentTarget.value;
if (validation) {
const errors = validate.single(value, validation);
if (errors) {
setError(errors[0]);
}
}
};
return (
<input
type="text"
onBlur={handleBlur}
onInput={e => setValue(e.target.value)}
onFocus={() => setError(null)}
/>
// show some error msg. if error is set
);
}
Form:
export default function CompetitionForm() {
const [formData, setFormData] = useState({});
const submitForm = async (e) => {
e.preventDefault();
// validate data, submit the form
};
const competitionTextInput = (key) => {
return (
<TextInput
name={key}
validation={RULES[key]}
onChange={value => {
formData[key] = value;
setFormData(formData);
}}
/>
);
};
return (
<form className="c-form" onSubmit={submitForm}>
<div className="row mb-4">
<div className="col-12 col-md-6">
{competitionTextInput('firstName')}
</div>
<div className="col-12 col-md-6">
{competitionTextInput('lastName')}
</div>
</div>
</form>
);
}