Yup validation check if not empty

yup
장수환 picture 장수환 · Jun 3, 2020 · Viewed 7.7k times · Source
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?

Answer

Dipesh KC picture Dipesh KC · Jun 3, 2020

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');
});