如何同时验证密码长度和正则表达式

How to validate password length and regex same time

我正在使用 yup 进行验证,它看起来像这样

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."),
  }),
)

但我想知道我们能否验证密码长度 (.min(8, "Password must be at least 8 charaters.") 和正则表达式 (

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

同时??比如把两个条件合二为一

非常感谢你

您可以使用以下正则表达式模式:

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

这需要大小写字母、数字、特殊字符以及总共 8 个或更多字符。正如上面的评论所建议的,如果您打算一次为每个规则提供反馈,您可能希望为每个条件分离出模式。