2023-04-27

Yup nested validation schema with conditional validation

I have created a formik object with initial values similar to

{customerDetails: {id: "", name: "", mobileNumber: ""}, notes: {id: "", text: "", type: ""}}

how do i write a conditional yup validation schema for this object such that if id of customerDetails is present name and mobile number are not required but required if id is not present.

I tried something like this:

const validationSchema = Yup.object().shape({
    customerDetails: Yup.object().shape({
        id: Yup.string(),
        firstName: Yup.string().when('id', {
            is: (value: string) => !Boolean(value),
            then: Yup.string().required("Required")
        }),
    })
})

but i am getting this error:

No overload matches this call.
  Overload 1 of 4, '(keys: string | string[], builder: ConditionBuilder<StringSchema<string, AnyObject, undefined, "">>): StringSchema<string, AnyObject, undefined, "">', gave the following error.
    Argument of type '{ is: (value: string) => boolean; then: Yup.StringSchema<string, Yup.AnyObject, undefined, "">; }' is not assignable to parameter of type 'ConditionBuilder<StringSchema<string, AnyObject, undefined, "">>'.
      Object literal may only specify known properties, and 'is' does not exist in type 'ConditionBuilder<StringSchema<string, AnyObject, undefined, "">>'.
  Overload 2 of 4, '(keys: string | string[], options: ConditionConfig<StringSchema<string, AnyObject, undefined, "">>): StringSchema<string, AnyObject, undefined, "">', gave the following error.
    Type 'StringSchema<string, AnyObject, undefined, "">' is not assignable to type '(schema: StringSchema<string, AnyObject, undefined, "">) => ISchema<any, any, any, any>'.
      Type 'StringSchema<string, AnyObject, undefined, "">' provides no match for the signature '(schema: StringSchema<string, AnyObject, undefined, "">): ISchema<any, any, any, any>'.ts(2769)
index.d.ts(296, 5): The expected type comes from property 'then' which is declared here on type 'ConditionConfig<StringSchema<string, AnyObject, undefined, "">>'


No comments:

Post a Comment