I'm working with react-hook-form and using YUP for front end validations. I have a scenario where I'm receiving a prop from back-end and and based on that prop I register my input field. I want to mark that field as required upon the form submission. But if I don't receive that prop that field should remain optional.
const subscriptionSchema = yup.object().shape({
premium_subscription: yup.bool(),
comments: yup.string(),
keep_your_plan: yup.string().required()
)}
premium subscription key is optional. That should be validated as required once we pass functional component a prop. How can we evaluate this field as optional or required in this scenario?
I solved my problem using ternary operator and decided on the basis of the prop whether it should be optional or required.
premiumSubscription: isRequired ? yup.string().required()
: yup.string().notRequired()
That solved my problem.