2

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'),
      }),
  },
);
Sweet Caramel
  • 206
  • 2
  • 11

1 Answers1

0

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 },
Sweet Caramel
  • 206
  • 2
  • 11