使用正则表达式使用匹配问题进行Yup验证

时间:2019-01-28 16:03:44

标签: javascript reactjs typescript validation yup

因此我在下面使用Yup进行了验证:

const myValidtion = yup
.string()
.trim()
.matches(/[abcdefghijklmnopqrstuvwxyz]+/ , 'Is not in correct format')
.required();

因此,这将按预期通过:hello world。但是令我感到困惑的是,为什么这也将通过:hello WORLD或这也将通过:hello ,&$#$ world

另一方面,如果我们仅输入无效字符,例如*%$&#$($#,则不会通过并显示错误。因此,正如我所看到的,这仅在 ALL 条目无效的情况下才出现错误。

我正在寻找的是如何使用Yup Match方法在用户输入例如hello ,*&) world

的情况下不通过

有人可以帮我吗?

2 个答案:

答案 0 :(得分:2)

您的正则表达式应使用^$来表示字符串的开始和结束,以覆盖整个字符串:

/^[abcdefghijklmnopqrstuvwxyz]+$/

否则,它将匹配字符串的一部分,这就是为什么当您混合使用好字符和坏字符时会匹配,但是当每个字符都不好时会失败的原因。

您可以使用以下字符范围来缩短正则表达式:

/^[a-z]+$/

您可以使用此online tool来构建和测试您的正则表达式。

答案 1 :(得分:0)

这对我有用:

const validationSchema = yup.object().shape({
  password: yup
    .string()
    .required("Please enter your password")
    .matches(
      /^.*(?=.{8,})((?=.*[!@#$%^&*()\-_=+{};:,<.>]){1})(?=.*\d)((?=.*[a-z]){1})((?=.*[A-Z]){1}).*$/,
      "Password must contain at least 8 characters, one uppercase, one number and one special case character"
    ),
  confirmPassword: yup
    .string()
    .required("Please confirm your password")
    .oneOf([yup.ref('password'), null], "Passwords don't match.")
});

您可以在https://regex101.com/r/rYT2yE/1上测试正则表达式代码。