简体   繁体   中英

Creating a strong password with Yup and Formik with individual error messages

What I have

I'm trying to create a password field which validates the strength of the input, in another answer I found the regex I can use to validate if the input meets specific conditions, the problem with this approach is that it throws only one error message for each of the validations.

password: yup
    .string()
    .required('Please Enter your password')
    .matches(
      /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/,
      "Must Contain 8 Characters, One Uppercase, One Lowercase, One Number and one special case Character"
    ),

What i want

what I want is validate each of the characters that the user enters and throw the specific errors if each of the conditions are fulfilled, eg if user inpunt is missing a lower case, it should throw the error 'must have a lower case', if the input is missing a number, it should throw the number 'must have a number' and so on. What I've tried it's to use match but this doesn't work:

password: yup
    .string()
    .required('Please Enter your password')
    .matches(/^[a-z]+$/, 'One lowercase character')
    .matches(/^[A-Z]+$/, 'One uppercase character')
    .matches(/^\d+$/, 'One number')
    // ... other validation

You just need to remove ^ (matches the beginning of input) and $ (matches the end of input) assertions from your code, like so:

password: Yup.string()
  .required("Required")
  .min(8, "Must be 8 characters or more")
  .matches(/[a-z]+/, "One lowercase character")
  .matches(/[A-Z]+/, "One uppercase character")
  .matches(/[@$!%*#?&]+/, "One special character")
  .matches(/\d+/, "One number"),

Here is a demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM