How to validate password length and regex same time

I'm using yup for validation, it look like this

export const signinSchema = yupResolver(
  yup.object().shape({
    username: yup.string().required("Email is a required field."),
    password: yup
      .string()
      .required("Password is a required field.")
      .matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@#$%^&+=])/, {
        message:
          "Password must be at least one uppercase, one lowercase, one special character and one number.",
      })
      .min(8, "Password must be at least 8 charaters."),
  }),
)

But i wonder can we validate password length ( .min(8, "Password must be at least 8 charaters." ) and regex (

.matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@#$%^&+=])/, {
        message:
          "Password must be at least one uppercase, one lowercase, one special character and one number.",
      })

At the same time?? like combine two condition into one

Thank you guy a lot

Upvotes: 1

Views: 2261

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520968

You could use the following regex pattern:

/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@#$%^&+=]).{8,}$/
                                                ^^^ change is here

This would require a lowercase and uppercase letter, digit, special character, and 8 or more total characters. As the comment above suggests, you might want to separate out the pattern for each condition, if you intend to provide feedback for each rule one at a time.

Upvotes: 2

Related Questions