Closed leonbloy closed 2 years ago
Hi @leonbloy,
I don't think there was ever any built-in support for default values. Could you please specify how it would translate to Yup validator. Then it should be easy to add. You can even try a simple experiment using a custom constraint handler function
I see there is a simple way to map it as described here: https://stackoverflow.com/questions/68136485/yup-validation-convert-empty-string-to-default-value
// Add method
yup.addMethod(yup.string, 'stripEmptyString', function () {
return this.transform((value) => (value === '' ? undefined : value));
});
// Usage
const mySchema = yup.object().shape({
name: yup.string('Name must be a string').stripEmptyString().default('John Doe')
});
I can see there was a simple attempt to add support for it here: https://github.com/kristianmandrup/schema-to-yup/blob/master/src/types/mixed/mixed.js#L285 to https://github.com/kristianmandrup/schema-to-yup/blob/master/src/types/mixed/mixed.js#L308
Line 209 results in addValueConstraint("default")
but that is hardly a valid call to addValueConstraint
as there is no value passed in. What should happen can be seen in https://github.com/kristianmandrup/schema-to-yup/blob/master/src/types/mixed/mixed.js#L263
addValueConstraint(propName, opts) {
const constraint = this.constraintBuilder.addValueConstraint(
propName,
opts
);
The fix should be in https://github.com/kristianmandrup/schema-to-yup/blob/master/src/types/mixed/mixed.js#L299
const fn = this[fnName];
const value = this.constraints[key];
constraintNames.map(constraintName => {
fn(constraintName, { value });
});
That should sort it.
The latest commit to master should contain a fix to this issue. Please try it out.
I've also renamed the method addValueConstraint
to addTrueValueConstraint
since it forces the value of the constraint to be true.
I also moved the default
constraint to a be "simple" constraint, ie. one that passes the unprocessed constraint value to addConstraint
.
get constraintsMap() {
return {
simple: ["default", "required", "notRequired", "nullable"],
trueValue: ["strict"]
};
}
I'm experiencing weird errors with schemas that include default values.
First, I start with this stripped version of the schema in the docs (which works ok)
This works for me, But iI breaks if I add any default to the string property:
It also breaks if I remove most restrictions from
age
attribute:I'm using schema-to-yup@1.11.5 with node 14, inside React with CRA 5 (webpack 5).