简体   繁体   中英

Yup confirm password validation

I am using Yup https://www.npmjs.com/package/yup and I read https://www.npmjs.com/package/yup-password to validate my formik forms.

I do not find a way to have two fields that should be equal to be valid:

  • newPassword
  • confirmNewPassword

Is there a way to test that both are equal?

You may combine yup.string().oneOf() and yup.ref() methods to achieve the same.

import * as yup from "yup";
import YupPassword from "yup-password";
YupPassword(yup);

const schema = yup.object().shape({
  password: yup.string().password().required(),
  confirmPassword: yup
    .string()
    .oneOf([yup.ref("password"), null], "Passwords must match"),
});

schema
  .validate({ password: "12345678aB1!", confirmPassword: "12345678aB1!" })
  .then(() => console.log("Valid"))
  .catch((err) => console.log(err.message));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM