Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
190
rated 0 times [  195] [ 5]  / answers: 1 / hits: 5773  / 4 Years ago, thu, june 18, 2020, 12:00:00

I'm trying to validate an object's field using yup.



These are my requirements:




  1. The field should either be a string or undefined.

  2. If it is undefined, it should be given a default value.

  3. 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!


More From » typescript

 Answers
6

I figured that you can extend the yup string as follows:



class StrictString extends yup.string {
constructor() {
super();
transforms = []; // remove the default type coercion transforms
}
}


And then, replace StrictString() with yup.string().
This will fit the requirements.


[#3445] Tuesday, June 16, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tobyl

Total Points: 598
Total Questions: 110
Total Answers: 114

Location: Vietnam
Member since Sat, Feb 12, 2022
2 Years ago
tobyl questions
Tue, Aug 10, 21, 00:00, 3 Years ago
Wed, Jan 13, 21, 00:00, 3 Years ago
Tue, Dec 1, 20, 00:00, 4 Years ago
;