0

I am doing a password validation schema, and I've got the following

const ProfileEditSchema = t =>
    Yup.object().shape({
       
        password: Yup.string()
            .notRequired(t('TR_PASSWORD_REQUIRED'))
            .matches(
                /^(?=.*[A-Za-z])(?=.*\d)[0-9a-zA-Z!@#$%-.()_']{8,}$/,
                t('TR_PASSWORD_HELPER')
            ),
        new_password: Yup.string().when('password', {
            is: password => password != undefined,
            then: Yup.string()
                .required(t('TR_PASSWORD_REQUIRED'))
                .matches(
                    /^(?=.*[A-Za-z])(?=.*\d)[0-9a-zA-Z!@#$%-.()_']{8,}$/,
                    t('TR_PASSWORD_HELPER')
                )
                .test(
                    'password-not-equal',
                    'new and old password are the same',
                    (password, new_password) => password === new_password
                )
        })

});

Everything works fine except my test function which whenever I set a new password value it keeps giving me the validation message error=> 'new and old password are the same' even I set different passwords. Also would appreciate if you can tell if using .test() in this case is the best aproach. All I want is to throw error in case two input values are equals. Thank you!

pepinillo6969
  • 423
  • 6
  • 15

1 Answers1

1

Noticed that you can't use other fields values as new_password in a .test() and also solutions explained as const {new_password}=this.parent, to get other fields value inside test didn't work because this returned undefined. So according to this I used in my code and substituted:

Instead of:

.test('password-not-equal','new and old password are the same',
          (password, new_password) => password === new_password)

I wrote:

.when('password', (password, schema) => {
                    return schema.test({
                        test: new_password => new_password !== password,
                        message: 'Passwords must be different'
                    });
                })
pepinillo6969
  • 423
  • 6
  • 15