'How to restrict formik validation when you click cancel button in react
from the field if you defocus without giving anything you are getting the validation error as well without giving value if you click on submit button you are getting validation error this is right ,but how to restrict the cancel button that without giving any data in the field if you click the cancel button then the validation error should not come ,how to restrict the formik validation only for cancel button or any kind of link.
can I use validateOnBlur particularly for cancel button, because in initial stage if i use that its disabling for all defocus kind of error, but I need only clicking on cancel that validation errors should not come. what approach should I follow.
import React from "react";
import { Formik, Form, Field } from 'formik';
import * as Yup from 'yup';
export default function DropDown() {
const SignupSchema = Yup.object().shape({
firstName: Yup.string()
.min(2, 'Too Short!')
.max(25, 'Too Long!')
.required('Name is required'),
});
return (
<>
<h1>Signup</h1>
<Formik
initialValues={{
firstName: '',
}}
//validateOnBlur={false}
validationSchema={SignupSchema}
onSubmit={values => {
console.log(values);
}}
>
{({ errors, touched }) => (
<Form>
<Field name="firstName" placeholder="type name" autoFocus="true" autoComplete="off"/>
{errors.firstName && touched.firstName ? (
<div style={{color:"red"}}>{errors.firstName}</div>
) : null}
<br/><br/>
<button type="submit" >Submit</button>
<button type="submit" >Cancel</button>
</Form>
)}
</Formik>
</>
);
}
Solution 1:[1]
You are using a "submit" type button which is triggering the form. Instead, you should use a "button" type:
<button type="button">Cancel</button>
Docs: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Button#attr-type
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pádraig Galvin |
