Search code examples
authenticationformik

Confirm Password with Formik


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;
}

Solution

  • 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>)}