3
votes

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 ?

2
Also discussed in this issuecolinD

2 Answers

3
votes

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.

3
votes

Testing exclusiveTests instead of _exclusive worked for me.

const isRequired = 
validationSchema?.fields[aField.name]?.exclusiveTests?.required || false;