简体   繁体   中英

yup conditional validation of array

I want to validate the array on the base of loan register if loan register is true then array should validate else not.

yup.object().shape({
                
                loan_register: yup.boolean(),
                loans: yup.array()
                    .of(
                        yup.object().shape({
                            bank_name: yup.string().required(),
                            bank_reg_no: yup.string().required(),
                            loan_amount: yup.string().required(),

                        })
                    )

            })

EDIT: ' When loan_register === true, bank_name, bank_reg_no and loan_amount must be strings and required fields. '

You can translate that requirement into code like following (include Yup conditional validation using .when() ):

    const validationSchema = yup.object().shape({        
         loan_register: yup.boolean(),
         loans: yup.array()
        .when('loan_register', {
            is: true,
            then: yup.of(
                yup.object().shape({
                    bank_name: yup.string().required(),
                    bank_reg_no: yup.string().required(),
                    loan_amount: yup.string().required(),
                })
             )
        })
    })

I think you'll want to utilize .when() . This allows exactly what you're looking for by providing conditional validation checks based off other attribute values.

It has a more explicit approach where you'd add

.when('loan_register', {is: true, then: /* yup schema */ })

I believe the change would look like

yup.object().shape({
    loan_register: yup.boolean(),
    loans: yup.array()
        .when('loan_register', {
            is: true,
            then: yup.of(
                yup.object().shape({
                    bank_name: yup.string().required(),
                    bank_reg_no: yup.string().required(),
                    loan_amount: yup.string().required(),
                })
            )
        })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM