Yup validate password contains at least one special character

Viewed 7079

I am using the following yup:

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'),
});

to validate if there is one special character in password string.

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

I also test the regex pattern online to make sure this pattern will catch any special character in string I wonder it could be yup bug or I do something wrong

2 Answers

You may try using the following regex pattern:

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

This just matches any input so long as it has a special character. Your updated React code:

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'),
});

You can try the below regex:

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

Explanation of the above regex:

^, $ - 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.

You can find the regex demo here.

Related