Search code examples
javascriptreactjsyupreact-hook-form

Access to required fields with Yup


I use react-hook-form with yup to validate my forms.

I want to know all required fields of a schema to display some information in form (like '*' for required fields). We could achieve this with this line of code :

schema.describe().fields[field].tests.findIndex(({ name }) => name === 'required'

However, this code doesn't work for conditional validation.

Schema example :

const schema = yup.object().shape({
    email: yup
    .string()
    .email()
    .required(),

    isProfileRequired: yup
    .boolean(),

    profile:  yup
    .object()
    .when('isProfileRequired',{
        is: (isProfileRequired) => isProfileRequired,
        then:
            yup
            .object()
            .nullable()
            .required()
    })
})

Is there a way to retrieve this informations within the form ?


Solution

  • There is actually no "nice" way to do it but this works:

    function isRequired(field){
        return schema.fields[field]._exclusive.required || false 
    }
    

    Notice: schema.fields[field]._exclusive.required returns true if required or undefined.