Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yup nested schema validation

I'm trying to validate an object conditionally on a Select Option that's been chosen by a user, the issue is I'm rendering a currency list and having immense difficulty trying to make it a required field, as I have to pass in an empty object to start with.

My code stack is React, Formik and Yup (all recent versions).

The Object Schema

category: 'A',
details: {
   name: '',
   price: 0,
   stock: 0,
   currency: {
      label: '',
      code: '',
      symbol: '',
      alpha_2: '',
    }
}

The Yup Schema

category: Yup.string().required('You must pick a category'),
details: Yup.object().when('category', {
  is: 'A',
  then: Yup.object({
       label: Yup.string().required(`Select the currency you're retailing in`),
        code: Yup.string().required(`Select the currency you're retailing in`),
        symbol: Yup.string().required(`Select the currency you're retailing in`),
        alpha_2: Yup.string().required(`Select the currency you're retailing in`),
    }),
})

With the above code the form is passing validation and the currency object has a list of empty values '', which is an undesired outcome.

How do you make the schema trigger validation?

like image 244
Xavier Avatar asked May 22 '20 19:05

Xavier


1 Answers

You are not validating against details.currency where label/code/symbol/alpha_2 are stored. In the schema.details, then should be composed of a Yup.object which has another Yup.object stored in currency property and then define the validations you want for label/code/symbol/alpha_2.

Example:

const yup = require("yup");

const schema = yup.object({
    category: yup.string().required('You must pick a category'),
    details: yup.object().when('category', {
        is: 'A',
        then: yup.object({
            currency: yup.object({
                label: yup.string().required(`[1] Select the currency you're retailing in`),
                code: yup.string().required(`[2] Select the currency you're retailing in`),
                symbol: yup.string().required(`[3] Select the currency you're retailing in`),
                alpha_2: yup.string().required(`[4] Select the currency you're retailing in`),
            })
        }),
    })
})

let state = {
    category: 'A',
    details: {
        name: '',
        price: 0,
        stock: 0,
        currency: {
            label: 'a',
            code: 'b',
            symbol: 'c',
            alpha_2: 'd',
        }
    }
}

schema.validate(state).then(console.log).catch(err => console.log(err))
like image 149
Gjergj Kadriu Avatar answered Nov 15 '22 09:11

Gjergj Kadriu