I am trying to make a multi-step form using that checks if the first two input fields are valid before moving on the the next step. The code below validates the two fields, but continues to the next step regardless if the forms are valid or not. I suspect the problem lies in the fact the onClick hook is changing the state without any checks. I do not know how to check if the fields are valid or not, before changing the state. I am using yup for validation alongside mantine for a component library.
const schema = yup.object().shape({
email: yup.string().email('Email is invalid.').required(),
password: yup.string().required(),
});
function Example() {
const [activeStep, setActiveStep] = useState(0);
const form = useForm({
schema: yupResolver(schema),
initialValues: {
email: "",
password: "",
firstName: "",
lastName: ""
}
});
return (
<form
onSubmit={form.onSubmit((values) => {
console.log(values);
})}
>
<Paper shadow="xs" p="md">
{activeStep === 0 && (
<>
<Title>Info</Title>
<Group>
<TextInput
label="Email"
{...form.getInputProps("email")}
/>
<TextInput
label="Password"
{...form.getInputProps("password")}
/>
</Group>
</>
)}
{activeStep === 1 && (
<>
{" "}
<Title>Personal</Title>
<Group>
<TextInput
label="First name"
{...form.getInputProps("firstName")}
/>
<TextInput
label="Last names"
{...form.getInputProps("lastName")}
/>
</Group>
</>
)}
<Group mt="xl">
<Button
onClick={() => setActiveStep((prev) => prev - 1)}
disabled={activeStep === 0}
>
Previous
</Button>
<Button
onClick={() => setActiveStep((prev) => prev + 1)}
type="submit"
disabled={activeStep === 1}
>
Next
</Button>
</Group>
</Paper>
</form>
);
}