Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 271
Strahinja Ajvaz Avatar asked Mar 27 '18 00:03

Strahinja Ajvaz


People also ask

How does Formik validate password and confirm password?

To compare if a password is the same as a confirmPassword we can use ref and reference our password field. We use the oneOf option and say that the confirmPassword should be oneOf a reference. Meaning it should match password.

How do you validate Formik field?

Formik supports field-level validation via the validate prop of <Field> / <FastField> components or useField hook. This function can be synchronous or asynchronous (return a Promise). It will run after any onChange and onBlur by default.

Can we use Yup without Formik?

Yes, you can use Yup without Formik, and you can use Formik without Yup.


2 Answers

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.

like image 92
Seva Avatar answered Sep 18 '22 00:09

Seva


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') }); 
like image 37
Harshal Avatar answered Sep 19 '22 00:09

Harshal