首页 > 解决方案 > 是的验证,一个字符串上有 2 个正则表达式

问题描述

我有这个架构可以根据几个要求验证 2 个密码字段:

现在我在一个字符串中显示两个验证错误,但我需要为这些条件显示 2 个单独的错误。

问题是,我如何创建 2 个在验证时不会相互冲突的正则表达式,并向我显示必要的错误?

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

标签: reactjsregexstringvalidationyup

解决方案


你可以试试这两个:

^(?=.*[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 _ @ . -"

推荐阅读