Formik, Yup Password Strength Validation with React

Okay, after a couple of hours of tinkering around, i decided to do my own custom validation instead.

Here is what i did :-

password: yup
    .string()
    .required("Please Enter your password")
    .test(
      "regex",
      "Password must be min 8 characters, and have 1 Special Character, 1 Uppercase, 1 Number and 1 Lowercase",
      val => {
        let regExp = new RegExp(
          "^(?=.*\\d)(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z]).{8,}$"
        );
        console.log(regExp.test(val), regExp, val);
        return regExp.test(val);
      }
    )

For now, this is working fine. But i would really like to know why the error is popping up. Please post it as an answer if you are able to find a solution, and if it works for me i will mark it as the right answer. Thanks.


This is what I finally got to work.

 password: Yup.string()
          .required('Please Enter your password')
          .matches(

            /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})/,
            "Must Contain 8 Characters, One Uppercase, One Lowercase, One Number and One Special Case Character"
          ),

I took this regex string from this article: https://www.thepolyglotdeveloper.com/2015/05/use-regex-to-test-password-strength-in-javascript/


You need to pass an actual RegExp object to matches, not a string. Just replace the double quotes with forward slashes in your password schema:

EDIT: Updated to use regex from @Bren

password: yup
    .string()
    .required('Please Enter your password')
    .matches(
      /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})/,
      "Must Contain 8 Characters, One Uppercase, One Lowercase, One Number and One Special Case Character"
    ),