Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yup validation check if not empty

Tags:

yup

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?

like image 862
장수환 Avatar asked Jun 03 '20 08:06

장수환


2 Answers

Alternative using trim()

const validationSchema = Yup.object().shape({
    newPassword: Yup.string().trim().required("Password must be at least 8 characters"),
  });
like image 155
Shaun Dychko Avatar answered Nov 19 '22 20:11

Shaun Dychko


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');
    });
like image 31
Dipesh KC Avatar answered Nov 19 '22 20:11

Dipesh KC