skip to Main Content

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


  1. Chosen as BEST ANSWER

    The best way I found is to extract sub-schemas from userSchema.fields and iterate over them


  2. Try this.

    userSchema.validate(data)
    .then(validData => {
    // The promise resolves with the valid data
    console.log('Valid data:', validData);
    
    // You can now use validData, which contains only valid fields.
    })
    .catch(errors => {
    // The promise rejects with an array of validation errors
    console.error('Validation errors:', errors);
    
    // Here you can choose to handle the errors or strip the invalid data.
    const strippedData = { ...data };
    for (const error of errors) {
      const { path } = error;
      delete strippedData[path];
    }
    
    console.log('Stripped data:', strippedData);
    });
    
    Login or Signup to reply.
  3. 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:

    import { object, string, number, date } 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 inputData = {
      name: 'jimmy',
      age: -1,
    };
    
    const parsedUser = await userSchema.validate(inputData, { stripUnknown: true });
    
    console.log(parsedUser);
    

    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:

    {
      name: 'jimmy'
    }
    
    Login or Signup to reply.
  4. You could use the stripUnknown options in yup.

    const options = {
      stripUnknown :true
    }
    
    const parsedUser = await userSchema.validate(
      {
        name: 'jimmy',
        age: -1,
      },options
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search