是的,验证密码至少包含一个特殊字符

Yup validate password contains at least one special character

我正在使用以下是的:

export const validationSchema = Yup.object().shape({
  password: Yup.string()
    .required('Password is required')
    .matches(
      /^[!@#$%^&*()_+\-=\[\]{};':"\|,.<>\/?]*$/,
      'Need one special character',
    ),
  confirmPassword: Yup.string()
    .oneOf([Yup.ref('password'), null], 'Passwords must match')
    .required('Password confirm is required'),
});

验证密码字符串中是否有特殊字符

@ => valid
@a => invalid
a@ => invalid
aa => invalid, of course

我还在线测试了正则表达式模式,以确保该模式能够捕获字符串中的任何特殊字符 我想知道这可能是错误还是我做错了什么

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

^.*[!@#$%^&*()_+\-=\[\]{};':"\|,.<>\/?].*$

这只匹配任何具有特殊字符的输入。您更新的 React 代码:

export const validationSchema = Yup.object().shape({
    password: Yup.string()
       .required('Password is required')
       .matches(
           /^.*[!@#$%^&*()_+\-=\[\]{};':"\|,.<>\/?].**$/,
          'Need one special character',
       ),
   confirmPassword: Yup.string()
      .oneOf([Yup.ref('password'), null], 'Passwords must match')
    .required('Password confirm is required'),
});

您可以试试下面的正则表达式:

^[0-9A-Za-z]*[!@#$%^&*()_+\-=\[\]{};':"\|,.<>\/?][0-9a-zA-Z]*$

上面正则表达式的解释:

^, $ - Matches start and end of the given string resp.

[0-9A-Za-z]* - Matches any character in the given range zero or more times.

[!@#$%^&*()_+\-=\[\]{};':"\|,.<>\/?] - Matches exactly one special character among the given set.

您可以找到正则表达式演示 here.