Sougata Mukherjee
Sougata Mukherjee

Reputation: 603

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>
        </>
      );
    }

Upvotes: 1

Views: 2968

Answers (2)

Ibrahim Azhar Armar
Ibrahim Azhar Armar

Reputation: 25745

When you use type="submit" Formik will immediately capture the event as submit and process for validation. Do not use type="submit" if you don't want to trigger the validation or want to trigger it manually.

If you have submitted the form, and if you want to reset the errors when user click on cancel then use setErrors

{({ errors, touched, setErrors })

Then invoke setErrors with empty arguments, when user click on cancel button

<button type="button" onClick={() => setErrors({})}>Cancel</button>

Upvotes: 2

P&#225;draig Galvin
P&#225;draig Galvin

Reputation: 1155

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

Upvotes: 0

Related Questions