I’m working on a multi-step form in React using react-hook-form, and I want to validate each step before allowing the user to proceed. I’m currently using the trigger method for validation, but I keep getting undefined when I try to call it. I don’t want to use a Zod resolver for validation.
Here is a snippet of my current implementation:
const form = useForm({
defaultValues: {
company: "",
first_name: '',
last_name: '',
email: '',
phone: '',
password: '',
password_confirmation: '',
country: '',
messenger: '',
messenger_id: '',
city: '',
street_address: '',
state: '',
zip_code: ''
},
});
const handleNextStep = async () => {
console.log(`Current step: ${step}`);
let isValid = false;
// Validate based on current step
if (step === 0) {
isValid = await form.trigger(['email', 'phone', 'messenger', 'messenger_id']);
} else if (step === 1) {
isValid = await form.trigger(['company', 'first_name', 'last_name', 'street_address', 'city']);
} else if (step === 3 || (step === 2 && !hasQuestions)) {
isValid = await form.trigger(['password', 'password_confirmation']);
}
console.log(`Form valid: ${isValid}`);
if (isValid) {
if (step < totalSteps - 1) {
setStep((prevStep) => prevStep + 1);
} else {
form.handleSubmit(onSubmit)();
}
} else {
console.log(`Please complete the current step before proceeding.`);
}
};
When I call form.trigger, it always returns undefined, preventing me from performing step validation. I need to ensure that users cannot proceed to the next step without completing the current one.
1.Why am I getting undefined when calling form.trigger?
2.What is the correct way to implement step validation in react-hook-form without using a resolver like Zod?
3.Are there any best practices or common pitfalls to avoid when validating multi-step forms with react-hook-form?
Thank you for your help!