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;
}
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With