Yup validation check if not empty

Viewed 35732
const validationSchema = Yup.object().shape({
    newPassword: Yup.string().min(8, 'Password must be at least 8 characters');
});

I want to validation check only if newPassword field is not empty. How could I do?

8 Answers

There are different approach on solving this problem.

Using test

const validationSchema = Yup.object().shape({
    newPassword: Yup.string().test(
        'empty-check',
        'Password must be at least 8 characters',
         password => password.length == 0
    });

Using when

const validationSchema = Yup.object().shape({
    newPassword: Yup.string().when('newPassword',{
        is:(password) => password.length > 0
        then: Yup.string().min(8, 'Password must be at least 8 characters');
    });

Alternative using test:

const validationSchema = Yup.object().shape({
    newPassword: Yup.string().test(
        'empty-or-8-characters-check',
        'Password must be at least 8 characters',
        password => !password || password.length >= 8,
    ),
});

Alternative using trim()

const validationSchema = Yup.object().shape({
    newPassword: Yup.string().trim().required("Password must be at least 8 characters"),
  });

There is a way of using .when() and not generating a cyclic dependency like the accepted answer, .shape() accepts an exhaustive list of dependencies as last argument, that resolves the cyclic conflict, the secret is using the same key twice https://github.com/jquense/yup/issues/176#issuecomment-369925782

const validationSchema = Yup.object().shape({
    newPassword: Yup.string().test(
        'empty-or-8-characters-check',
        'Password must be at least 8 characters',
        password => !password || password.length >= 8,
    ),
}, [["newPassword","newPassword"]]);

The way I solved this for myself was to first add .nullable() and then .transform() empty string into a null.

const validationSchema = Yup.object().shape({
    newPassword: Yup
        .string()
        .nullable()
        .transform((v, o) => (o === '' ? null : v))
        .min(8, 'Password must be at least 8 characters')
});

I used the Yup function nullable() so it is only validated with the next functions if it not null:

kmBegin: Yup.number().nullable().positive().integer(),
parcelTotal: Yup.number().positive().integer(),
timeBegin: Yup.date(),
timeEnd: Yup.date().nullable(),

The simplest way is:

const validationSchema = Yup.object().shape({
    newPassword: Yup
     .string()
     .matches(/^\w{8}/, "Password must be at least 8 characters")
});

Alternative that won't allow 8 empty characters.

const notEmpty = Yup.string()
  .ensure() // Transforms undefined and null values to an empty string.
  .test('Only Empty?', 'Cannot be only empty characters', (value) => {
    const isValid = value.split(' ').join('').length !== 0;

    return isValid;
  });

const validationSchema = Yup.object({
    newPassword: notEmpty.min(8, 'Password must be at least 8 characters');
});
Related