I'm using Ionic 7, React 18, and REact hook forms v 7.48. I would like to validate my form upon submit, but also display error messages if the user touches the control and doesn't enter the input correctly. I constructed my form like so ...
const {
control,
handleSubmit,
formState: { errors },
} = useForm();
...
<form onSubmit={handleSubmit(handleSaveAndContinue)}>
...
<Controller
name="firstName"
control={control}
rules={{
required: { value: true, message: "Required" },
}}
render={({ field }) => (
<RequiredTextInput
label="Last Name"
placeholder="Last Name"
initialValue={contactInfo.lastName}
onChange={(lastName) =>
setContactInfo({ ...contactInfo, lastName })
}
/>
)}
/>
...
<IonButton type="submit">Save and Continue</IonButton>
</form>
and defined this text input control to take advantage of Ionic's ability to display an error message ...
function RequiredTextInput({
label,
placeholder,
initialValue = "",
onChange,
}: RequiredTextInputProps) {
const [isTouched, setIsTouched] = useState(false);
const [isValid, setIsValid] = useState<boolean | undefined>(undefined);
const [value, setValue] = useState(initialValue);
const validate = (val: string) => {
setIsValid(undefined);
const isValid = isTouched && val !== "";
setIsValid(isValid);
};
const markTouched = () => {
setIsTouched(true);
};
useEffect(() => {
validate(value);
}, [value]);
return (
<IonInput
placeholder={placeholder}
value={value}
className={`${isValid && "ion-valid"} ${
isValid === false && "ion-invalid"
} ${isTouched && "ion-touched"}`}
type="text"
fill="solid"
label={label}
labelPlacement="floating"
helperText="Enter a non-empty value."
errorText="Field is required"
onIonChange={(event) => {
const inputValue = event.detail.value!;
setValue(inputValue);
// Call the validate method
validate(inputValue);
// Call the onChange prop
if (onChange) {
onChange(inputValue);
}
}}
onIonBlur={() => markTouched()}
/>
);
}
export default RequiredTextInput;
HOwever, if I click the submit button without touching any of the controls, my error message for this particular control doesn't display. Not quite sure the proper way to wire this up between Ionic and the React hook form facility.