21
votes

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

3

3 Answers

37
votes

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.

27
votes

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

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