Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add and remove validation field to yup.validationSchema

How to add and remove validation field to yup.validationSchema

const validationSchema = yup.object().shape({
    password: yup
        .string()
        .label('Password')
        .required()
        .min(2, 'Seems a bit short...')
        .max(10, 'We prefer insecure system, try a shorter password.'),
    });
like image 435
Day's Night Avatar asked Dec 03 '22 10:12

Day's Night


2 Answers

for adding validation you can use concat, checkout the documentation here:

https://github.com/jquense/yup#mixedconcatschema-schema-schema

You can define your basic validation and add additional validations later on. Be carefully that you are just concat of the same type.

Example:

const requiredSchema = Yup.string().required();
const min2Schema     = Yup.string().min(2, 'Seems a bit short...');
const passwordSchema = Yup.string()
                 .label('Password')
                 .max(10, 'We prefer insecure system, try a shorter password.')
                 .concat(requiredSchema)
                 .concat(min2Schema);

All that schemas are .string() schemas. You can just concat an object with objects, string with strings, number with numbers etc.

For making conditional validations, you can just add an inline-condition:

let isRequired = true;

const nameAndPasswordSchemaObject = Yup.object().shape({
    name: nameSchema.concat( isRequired ? requiredSchema : null ),
    password: passwordSchema,
});

The same goes for yup-objects:

const emailSchemaObject = Yup.object({
   email: Yup.string().concat(requiredSchema)
});

const validationSchema = nameAndPasswordSchemaObject.concat(emailSchemaObject);

I hope that helps.

About removing schemas I couldn't see anything in the documentation (but never needed it)

like image 168
Stefan Avatar answered Dec 04 '22 23:12

Stefan


For someone that looking for another approach, like dependent on value inside the schema itself

import * as yup from 'yup';

export const Schema = yup
  .object()
  .shape({
    name: yup.string().lowercase().required(),
    phone: yup.number().default(0).required(),
  })
  .when((values, schema) => {
    if (values.name === 'john') {
      return schema.shape({
        isHungry: yup.boolean().required(),
        food: yup.string().default('Pizza'),
      });
    }
  });
like image 23
Wachid Avatar answered Dec 04 '22 22:12

Wachid