kyw
kyw

Reputation: 7543

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;
}

Upvotes: 6

Views: 5804

Answers (1)

kyw
kyw

Reputation: 7543

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 :)

Upvotes: 1

Related Questions