Alberto Manuguerra
Alberto Manuguerra

Reputation: 149

Yup validation based on value of another field

I've three fields : referenceMonth(string), openingDate(string), closingDate(string) in Formik form. I would add an error to openingDate when openingDat isn't the same month as referenceMonth.

export const VALIDATION_SCHEMA = Yup.object().shape({
    'referenceMonth' : Yup.number().required(YUP_DEFAULT_ERROR_VALUE),
    'openingDate' : Yup.string().when(['referenceMonth', 'openingDate'], {
        is: (referenceMonth: string, openingDate: string) => 
             referenceMonth !== `${new Date(openingDate).getMonth()}`,
        then: Yup.string().required('Select right month')
    }),
})

Terminal says: Error: Cyclic dependency, node was: "openingDate".

Upvotes: 8

Views: 27264

Answers (3)

Kalpesh Chavda
Kalpesh Chavda

Reputation: 11

category: Yup.string().required("Category is required"),
  topics: Yup.array().test("required", "Topics are required", (value, validationContext) => {
    const {
      parent: { category },
    } = validationContext;
    return category !== "" && category !== undefined && value.length !== 0;
  }),

Upvotes: 1

Rishabh Singh
Rishabh Singh

Reputation: 391

Since your validation for openingDate is pretty stright forward as in the schema for openingDate won't change (as per my understanding), i would suggest you to make use of test rather than when. You could replace your when with test like so

.test("dateTest", "Select right month", function (value) {
   return this.parent.referenceMonth !== `${new Date(value).getMonth()}`;
 })

Upvotes: 7

Yedhin
Yedhin

Reputation: 3199

Fields that depend on each other, to be validated, needs to be sorted so that they are constructed in in the desired order. Can you try it this way by adding the fields that need validation at the end in that specific order:

export const VALIDATION_SCHEMA = Yup.object().shape({
    'referenceMonth' : Yup.number().required(YUP_DEFAULT_ERROR_VALUE),
    'openingDate' : Yup.string().when(['referenceMonth', 'openingDate'], {
        is: (referenceMonth, openingDate) => 
             referenceMonth !== `${new Date(openingDate).getMonth()}`,
        then: Yup.string().required('Select right month')
    }),
}, [['referenceMonth', 'openingDate']])

Upvotes: 11

Related Questions