Home > Software design >  How to validate only a part of Yup schema?
How to validate only a part of Yup schema?

Time:12-19

Considering we have the following defined schema in React:

const InsertSchema = Yup.object().shape({
    category: Yup.string()
        .required("Category is required."),
    usage: Yup.number()
        .required("Usage is required."),
});

Let us say I want to validate in a given form only the category field, is there any way to do it without defining another schema that only contains the category field?

const handle = async () => {
        try {
            await InsertSchema.validate({
                category
            }, { abortEarly: false });
        } catch (e) {
            let errors = getYupValidationErrors(e);
            setInputErrors(errors);
        }
    }

Currently, only specifying the category in the handle function returns two validation errors: Category is required, Usage is required. I need it only to display category is required.

CodePudding user response:

Maybe you can use Schema.when(keys: string | string[], builder: object | (values: any[], schema) => Schema): Schema. https://github.com/jquense/yup#schemawhenkeys-string--string-builder-object--values-any-schema--schema-schema

example :

const InsertSchema = Yup.object().shape({
    category: Yup.string()
        .required("Category is required."),
    usage: Yup.number().when('isUsageNotRequired', {
      is: true, 
      then: (schema) => schema,
      otherwise: (schema) => schema.required("Usage is required."),
    })
});

const handle = async () => {
  try {
      await InsertSchema.validate({
          // if true usage will not be required, if false or undefined it will be required
          isUsageNotRequired: true,
          category: 'test',
      }, { abortEarly: false });
  } catch (e) {
       console.log('e : ', e)
  }
}

Hope it will help you.

CodePudding user response:

Create two separate schemas, then concat them:

const CategorySchema = Yup.object().shape({
    category: Yup.string().required("Category is required."),
});
const UsageSchema = Yup.object().shape({
    usage: Yup.number().required("Usage is required."),
});
const InsertSchema = CategorySchema.concat(UsageSchema);

Now you can choose which schema to validate against - the complete InsertSchema or only the CategorySchema.

  • Related