简体   繁体   中英

password validation with yup and formik

how would one go about having password validation but at the same time having the errors be passed to different variables?

ie

password: Yup.string().required("Please provide a valid password"),
passwordMin: Yup.string().oneOf([Yup.ref('password'), null]).min(8, 'Error'),
passwordLC: Yup.string().oneOf([Yup.ref('password'), null]).matches(/[a-z]/, "Error" )
passwordUC: Yup.string().oneOf([Yup.ref('password'), null]).matches(/[A-Z]/, "Error" )

I cant get the binding of the password variables to bind with the password object

Just to elaborate on efleurine's answer.
You do not need to store each validation on the same field - you can chain them to get a full validation.

password: Yup.string()
  .required('No password provided.') 
  .min(8, 'Password is too short - should be 8 chars minimum.')
  .matches(/[a-zA-Z]/, 'Password can only contain Latin letters.')

Note how you still can specify individual messages for each failure.
Also, for the binding to work, make sure the form input you're binding to has an appropriate name attribute - in this case, password .

Hope this helps:

import * as Yup from 'yup';

validationSchema: Yup.object({
  password: Yup.string().required('Password is required'),
  passwordConfirmation: Yup.string()
     .oneOf([Yup.ref('password'), null], 'Passwords must match')
});

I use yup-password for this. Example:

import * as Yup from 'yup';
import YupPassword from 'yup-password';
YupPassword(Yup);

const requiredField = () => Yup.string().required('required');    
const passwordField = () =>
  requiredField()
    .min(
      8,
      'password must contain 8 or more characters with at least one of each: uppercase, lowercase, number and special'
    )
    .minLowercase(1, 'password must contain at least 1 lower case letter')
    .minUppercase(1, 'password must contain at least 1 upper case letter')
    .minNumbers(1, 'password must contain at least 1 number')
    .minSymbols(1, 'password must contain at least 1 special character');

In this example I'm validating for min number of characters, lower and uppercase chars, numbers and symbols, but you can add or remove specifications. You can set a maximum amount of chars, for instance.

The beauty of this library is that you get to specify the error message, and it also handles special characters for you, which is great because it saves you from using RegEx. Have fun!

I know you can chain validations together for the same element. If you are trying to do cross-validation then this article would help you. it about formik in react but I bet it would give you an idea how to solve your case.

https://itnext.io/simple-react-form-validation-with-formik-yup-and-or-spected-206ebe9e7dcc

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