'How to dynamically validate a form with Yup?

I get an object with random properties (keys) and I would like to validate, this is an example of what I can get:

{
    "underlying_ticker": "",
    "barrier": "",
    "fixing_date": "3223",
    "maturity_date": "2323",
    "payment_date": "2332",
    "put_barrier": "2323",
    "put_strike": "3232",
    "quantity": "2323",
    "strike": "32"
}

I would like to know how I can validate them to know if they are filled and so on.

I tried the following code below:

  const validateForm = async (data) => {
    try {
      parametersFormRef.current.setErrors({});

      const shapes = Object.keys(data).map(((parameter) => {
        return ({ [parameter]: Yup.string().typeError("Test").required() });
      }));

      const schema = Yup.object().shape({ ...shapes });

      await schema.validate(data, { abortEarly: false });
    } catch (err) {
      console.error(err);
      const validationErrors = {};

      if (err instanceof Yup.ValidationError) {
        err.inner.forEach((error) => {
          validationErrors[error.path] = error.message;
        });
      }
    }
  };

However, it is not falling into catch, even with both empty values.



Solution 1:[1]

    const schema = Yup.lazy((value) => {
       const shapes = {};
       const DATA_OBJ_KEYS = Object.keys(value);
    
       DATA_OBJ_KEYS.forEach(((parameter) => {
         shapes[parameter] = Yup.string().required('Campo Obrigatório');
        }));
    
        return Yup.object().shape(shapes);
     });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 THIAGO DE BONIS