Is it possible with Yup to validate an object and keep all valid data and ignore invalid data and strip them?
In the following example I would like to keep jimmy
and name
because it is valid and strip age
from result object, as it is invalid
import { object, string, number, date, InferType } from 'yup';
const userSchema = object({
name: string().required(),
age: number().required().positive().integer(),
email: string().email(),
website: string().url().nullable(),
createdOn: date().default(() => new Date()),
});
const parsedUser = await userSchema.validate(
{
name: 'jimmy',
age: -1,
},
);
4
Answers
The best way I found is to extract sub-schemas from
userSchema.fields
and iterate over themTry this.
Yes, you can achieve this behavior with Yup by using the stripUnknown option. Setting stripUnknown to true will remove any keys in the input object that are not defined in your schema. In your case, it will remove the "age" key because it doesn’t match the schema, and it will keep the other valid keys such as "name."
Here’s how you can modify your code to achieve this:
With stripUnknown: true, the "age" key will be removed from the parsedUser object because it’s not part of the schema, and you will only get the following output:
You could use the stripUnknown options in yup.