jquense / yup

Dead simple Object schema validation
MIT License
22.73k stars 926 forks source link

yup.object().when return a wrong type #2169

Closed michelecocuccio closed 7 months ago

michelecocuccio commented 7 months ago

Hello I have the following schema which uses when

export const nuovoCespiteSchema = yup.object({
  asset: yup.string().required("È obbligatorio selezionare un cespite"),
  genericForm: yup.object().when("asset", {
    is: (value: AssetTypesEntity) =>
      value === AssetTypesEntity.PHOTOVOLTAIC_IMPLANT ||
      value === AssetTypesEntity.BIOGAS_IMPLANT ||
      value === AssetTypesEntity.CHARGING_STATION,
    then: () =>
      yup.object({
        serial: yup.string().required("Il numero di matricola è obbligatorio"),
        installationDate: yup
          .date()
          .required("La data di installazione è obbligatoria"),
        locationNation: yup
          .string()
          .required("La nazione di ubicazione è obbligatoria"),
        locationProvince: yup
          .string()
          .required("La provincia di ubicazione è obbligatoria"),
        locationCity: yup
          .string()
          .required("Il comune di ubicazione è obbligatorio"),
        locationAddress: yup
          .string()
          .required("L'indirizzo di ubicazione è obbligatorio"),
        locationZipCode: yup
          .string()
          .typeError("Il CAP di ubicazione deve essere un numero valido")
          .min(5, "Il CAP di ubicazione deve contenere 5 caratteri")
          .max(5, "Il CAP di ubicazione deve contenere 5 caratteri")
          .required("Il CAP di ubicazione è obbligatorio"),
        power: yup.string().required("La potenza dell'impianto è obbligatoria"),
        installationValue: yup
          .number()
          .required("Il valore dell'impianto è obbligatorio"),
        details: yup
          .string()
          .max(500, "Le note devono essere lunghe al massimo 500 caratteri"),
      }),
    otherwise: () => yup.object(), // Empty schema for other cases
  }),

  coverages: yup.array(),
});

the problem is that It gives back only an empty object for the genericForm

Screenshot 2024-01-26 at 18 39 42 while I was expecting either an empty object or something like this Screenshot 2024-01-26 at 18 41 03

the problem is due to the fact that then React Hook Form has the wrong type as in only gets {} as type.

const methods = useForm({
    resolver: yupResolver(nuovoCespiteSchema),
    mode: "onChange",
    reValidateMode: "onChange",
  });

Am I doing something wrong? thanks for the help!

Screenshot 2024-01-26 at 18 43 21