Confirm Password with Formik

Viewed 10683

I'm trying to use formik's field validation to confirm password authentication. But i was having trouble trying to compare the password and confirm password

So far I have register.js

<Formik
        initialValues={{
        password: "",
        confirmPassword: "",
        }}
        onSubmit={(values, actions, { validate }) => {
                    validate(values);
                    register(values);
                    actions.resetForm();
                }}
       >
                {({ errors, touched, validateForm }) => (
                    <Form className={styles.form}>

        <Field
              type="password"
              name="password"
              validate={validatePassword}
              />            
        <Field
              type="password"
              name="confirmPassword"
              validatePassword={confirmPassword}
              />                        
          <button type="submit" onClick={() => validateForm()}>
                            {!isLoading ? "Register" : <Loader />}
                        </button>
                    </Form>
                )}
            </Formik>

with validation looking like this.

function validatePassword(values) {
    let error = {};
    const passwordRegex = /(?=.*[0-9])/;
    if (!values) {
        error = "*Required";
    } else if (values.length < 8) {
        error = "*Password must be 8 characters long.";
    } else if (!passwordRegex.test(values)) {
        error = "*Invalid password. Must contain one number.";
    }
    return error;
}
2 Answers

Function to validate a password

const validatePassword = values => {
  let error = "";
  const passwordRegex = /(?=.*[0-9])/;
  if (!values) {
    error = "*Required";
  } else if (values.length < 8) {
    error = "*Password must be 8 characters long.";
  } else if (!passwordRegex.test(values)) {
    error = "*Invalid password. Must contain one number.";
  }
  return error;
};

Function to validate a confirm password

const validateConfirmPassword = (pass, value) => {

  let error = "";
  if (pass && value) {
    if (pass !== value) {
      error = "Password not matched";
    }
  }
  return error;
};

Plug those validation functions to their respective Field

 <Field type="password" name="password" validate={validatePassword} />

 {errors.password && <div>{errors.password}</div>}

 <Field type="password" name="confirmPassword" validate={value =>
              validateConfirmPassword(values.password, value)
            }/>

 {errors.confirmPassword && (<div>{errors.confirmPassword}</div>)}

import * as yup from 'yup';

const validationSchema = yup.object({
password: yup
  .string()
  .required('Password is required')
  .min(5, 'Your password is too short.'),
  .matches(/[a-zA-Z]/, 'Password can only contain Latin letters.')
confirmpassword: yup
  .string()
  .oneOf([yup.ref('password'), null], 'Passwords must match')
});

In your Yup Validation Schema you can use above way which is a Formik way checking the Password Match validation

Related