Yup validation based on value of another field
Asked Answered
A

3

8

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".

Agle answered 2/4, 2021 at 9:49 Comment(1)
Does this answer your question? Get the value of another field for validation in Yup SchemaFractional
V
11

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']])

Violaviolable answered 2/4, 2021 at 10:9 Comment(0)
S
7

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()}`;
 })
Scutum answered 2/4, 2021 at 10:16 Comment(1)
Nice solution with this.parent. !Gourmet
H
1
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;
  }),
Hessian answered 2/9 at 4:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.