password validation with yup and formik

Strahinja Ajvaz picture Strahinja Ajvaz · Mar 27, 2018 · Viewed 23.1k times · Source

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

Answer

VBorisoff picture VBorisoff · Dec 2, 2018

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.