Multi step form - How to disable "next" button if current visible inputs aren't valid
Answered
Rhinelander posted this in #help-forum
RhinelanderOP
I made multi step form. I navigate between steps with "back" and "next" buttons. I want to disable next button if current visible inputs aren't valid. Currently validation is applied but i can still navigate forward and back between steps. I could use field value and for each one individual check if it is valid but this seems very inefficient any other suggestions.
Just for visualization purposes here is my code
Just for visualization purposes here is my code
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
{currentStep}
<div className="flex justify-between gap-4">
{!isFirstStep && (
<Button type="button" variant="outline" onClick={back}>
Back
</Button>
)}
{!isLastStep ? (
<Button onClick={next}>Next</Button>
) : (
<Button>Submit</Button>
)}
</div>
</form>
</Form>
);
Answered by Anay-208
Its better if you divide it into 2 components, and create different zod schema, and merge them in main component
20 Replies
Zod, Yup, react hook forms and those have an isValid method that check your schema conditions
I recommend using
useStep
It'll help you with validations
RhinelanderOP
I face problem that normal button submits when submit buttom is visible if i comment it out it works fine.
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
{steps[currentStep - 1].component}
<div className="flex justify-end gap-4">
{currentStep > 1 && (
<Button type="button" variant="outline" onClick={goToPrevStep}>
Back
</Button>
)}
{currentStep === steps.length ? (
<Button type="submit">Submit</Button>
) : (
<Button type="button" onClick={goToNextStep}>
Next
</Button>
)}
</div>
</form>
I am using this... with my previous setup i didn't have problem
Oh and for disabling next button, You can use zod to create schema
if there are any errors in schema, just disable it
RhinelanderOP
but it will disabled it in every case as next step is not yet touched
Umm, I didn't get you
RhinelanderOP
I have multi step form. if i try to disable button for the first step it will stay disabled as there is second step. This is not 2 seperate forms but 1 form with 2 steps
Ahh got it.
Its better if you divide it into 2 components, and create different zod schema, and merge them in main component
Answer
RhinelanderOP
Well step 3 is payment and if payment isn't compleate I don't create any of that before. else random folks could populate my db and all i have is costs of resources from them
Did you mean another form or just splitted component inside one form
So don't create any of that?
only create when payment is completed
@Rhinelander updates?
RhinelanderOP
I am still woeking on that. Loosing my mind but sure