Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically extend or compose a Yup schema

Say I have a Yup.string() to begin with.

Then, at some point, like in a loop, I wanna add required rule to it, effectively:

Yup.string().required('This field is required').

And maybe then add some .email check too.

I have tried this way but didn't seem to work:

function validationSchemaConstructor(question) {
  const schema = Yup.string();

  question.validation_rules.forEach(rule => {
    if ("is_required" in rule) {
      schema.required("Hey man nice shot");
    }
  });

  return schema;
}
like image 606
kyw Avatar asked Apr 05 '19 05:04

kyw


1 Answers

Ah my mistake- I need to assign the schema again cuz chaining in general works by returning the object again:

function validationSchemaConstructor(question) {
  let schema = Yup.string();

  question.validation_rules.forEach(rule => {
    if ("is_required" in rule) {
      schema = schema.required("Hey man nice shot");  // mistake here!
    }
  });

  // un-comment to test dynamically adding additional rule
  // schema = schema.email("email plesss");

  return schema;
}

Though not sure if I should use the clone() somewhere.

Please advice if there's a better way :)

like image 115
kyw Avatar answered Oct 20 '22 22:10

kyw