javascriptformikyup

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?

i.e

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


Solution

  • 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.