I use useForm, but I don't think it matters. I want dependence on isAdmin to validate fields: paymentMethod, otherPaymentMethod. I tried with context: { isAdmin: true }
and to get it in transform((value) => { console.log(value); })
but nothing. How correct to pass value { isAdmin: true }
to schema?
const {
handleSubmit,
control,
setValue,
formState: { errors },
} = useForm({
context: { isAdmin: true },
resolver: yupResolver(schema),
mode: 'onBlur',
});
import { object, string } from 'yup';
export const schema = object().shape(
{
isAdmin: string().transform((value) => {
console.log(value);
}),
facility: object().nullable().required('Required!'),
paymentMethod: object().nullable().required('Required!'),
otherPaymentMethod: string()
.when('paymentMethod', {
is: (obj) => obj?.value === '-1',
then: string().nullable().required('Required'),
}),
},
);
I created the schema
as a function and passed isAdmin
as an argument:
export const schema = (isAdmin) => object().shape(
{
facility: object().nullable().required('Required!'),
paymentMethod: isAdmin ? object().nullable().required('Required!') : object().nullable().notRequired(),
otherPaymentMethod: string()
.when('paymentMethod', {
is: (obj) => obj?.value === '-1',
then: string().nullable().required('Required'),
}),
},
);
and passed value:
resolver: yupResolver(schema(isAdmin)),
removed context:
context: { isAdmin: true },
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With