I have a form. But when i am forwarding it to success page it is not validating forum and moving it to success page and below is my code. can some one please help me?
Below is my detailed validation page and in the sucess page and below is my routing
<Link to="/success">
<Button variant="primary" type="submit">
Submit
</Button>
</Link>
CodePudding user response:
You usually validate either on change of a field (before you even submit) or on submit. If latter, you define your logic in the onSubmit function of the form:
export default function Form() {
const handleSubmit = (event) => {
event.preventDefault();
// do your validation here
// conditionally do what you want
// for example navigate to other page:
// history.push("/success");
}
return (
<Form onSubmit={handleSubmit}>
...
<Button type="submit">Submit</Button>
</Form>
);
}
You don't need to wrap your Button with Link. Button with type="submit" automatically calls the onSubmit function of the form.
Edit: I have corrected your sandbox and now it's working: https://codesandbox.io/s/charming-curran-1hfe6j
I set the route to the form as "/" so it is initially shown when you load your app:
<Routes>
<Route path="/" element={<MyForm />} />
<Route path="/success" element={<Success />} />
</Routes>
- Your variables were not named the same in initialValues, field'name and validate function (name <-> username), I adjusted them
I have used Form.Control.Feedback to render error feedback in your form and set the isInvalid property in the Form.Control
<Form.Control
...
isInvalid={!!formErrors.name}
/>
and
<Form.Control.Feedback type="invalid">
{formErrors.name}
</Form.Control.Feedback>
Add noValidate property on your Form component, to prevent default HTML validation
<Form onSubmit={handleSubmit} noValidate className="p-3">
Validation is performed on submit, no compex useEffect hook needed
const handleSubmit = (e) => {
e.preventDefault();
const errors = validate(formValues);
setFormErrors(errors);
console.log(!errors);
if (Object.keys(errors).length === 0) {
navigate("success");
}
};