1
votes

I have this schema that validates 2 password fields based on several requirements :

  • "Password must have 8 or more characters, at least one uppercase letter, and one number."
  • "Password cannot contain special characters other than _ @ . -"

Right now i am showing both validation errors in one string, but i need to show 2 separate errors for these conditions.

The question is, how do i create 2 regex that don't conflict with each other when validating and will show me the necessary error?

  const format = /[a-z`!#$%^&*()+=\[\]{};':"\\|,<>\/?~]/;
  const passwordFormat = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\[email protected]]{8,}$/;

  return yup.object().shape({
    password: yup
      .string()
      .required("Password is required")
// validates the password
      .matches(passwordFormat, "Password must have 8 or more characters, at least one uppercase letter, and one number.")
//checks if there are special characters
      .test('special-chars', "Password cannot contain special characters other than _ @ . -", function(value) {
        return format.test(value);
      })
      .strict(true)
  });
1

1 Answers

2
votes

You can try these two:

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\S]{8,}$ - "Password must have 8 or more characters, at least one uppercase letter, and one number"

^[-@\.\w]*$ - "Password cannot contain special characters other than _ @ . -"