I'm trying to validate an object's field using yup.
These are my requirements:
- The field should either be a string or undefined.
- If it is undefined, it should be given a default value.
- If it is a value of some other type, it should not be coerced into a string. Instead, it should be incompatible and should result in an error.
I've tried the following so far:
A. The following schema does not prevent type coercion. e.g. when the value is a number, it passes the validation. However, I want it to fail the validation.
const schema = yup.object().shape({
myField: yup.string().default('myDefaultString')
});
B. The following schema prevents type coercion, but it fails when I pass an undefined value. I actually want the value to be 'myDefaultString' if an undefined value is given.
const schema = yup.object().shape({
myField: yup.string().strict(true).default('myDefaultString')
});
C. The following schema has the same result as option B.
const schema = yup.object().shape({
myField: yup.string().strict(true).notRequired().default('myDefaultString')
});
D. Use strict: true
as part of the options when using validateSync
method to validate the schema. Again, this has the same result as B.
Would appreciate any help with this, thanks!