0
votes

I have 3 input fields (name, id, and postcode), and I use formik along with Yup for the validation.

What I want to achieve here is, I want to match each input field with a known combination of name, id and postcode (I have a predefined default value for id, name, postcode).

And if the values entered on all the 3 input fields exactly match with the default values of name, id, and postcode, then I have to show the formik error on each of the fields(*something like default not allowed). If one of these fields is different from the default values, do not show the error on any fields.

For eg, if my default values for each fields are name="testName", id="testID", postCode="testPostCode", show validation error on each field only if all 3 input values matches with the defaultValues.

This is what I've now:

const defaultValues = {
  name: 'testName',
  id: 'testID',
  postCode: 'testPostCode'
}

const YUP_STRING = Yup.string().ensure().trim();

const validationSchema = yup.object().shape({
   name: YUP_STRING.required('required'),
   id: YUP_STRING.required('required'),
   postcode: YUP_STRING.required('required'),
})

I've tried several variations, but nothing worked here. Can anyone help me find a solution for this?

1

1 Answers

0
votes

You can do something like <Field validate={(value)=>validate(value,values)} name="name" type="text" />

In more detail..

<Formik
     initialValues={defaultValues}
     onSubmit={values => alert(JSON.stringify(values)}
   >
     {({ errors, touched, values }) => (
       <Form>
         <Field validate={(value) => validate(value, values)} name="name" type="text" />
         {errors.name && touched.name ? <div>{errors.name}</div> : null}
         <button type="submit">Submit</button>
       </Form>
     )}
</Formik>

And define validate function as

const validate = (value, values) => {
  if(values === defaultValues){
    return "Default Values not allowed"
  } else return undefined
}

Or if you want to do it with validationSchema you can do something as by adding test function on each of the field, I have only done for name:

const validationSchema = yup.object().shape({
   name: YUP_STRING.required('required')
         .test('name', "No default please", function (item) {
                   const currentValues = {
                       name: this.parent.name,
                       id: this.parent.id,
                       postCode: this.parent.postCode
                     }
                   return !(currentValues === defaultValues)
              }
          ),
   id: YUP_STRING.required('required'),
   postcode: YUP_STRING.required('required'),
})

No arrow function to be able to use this