Categories
React Answers

How to add password strength validation with React, Formik and Yup?

Spread the love

Sometimes, we want to add password strength validation with React, Formik and Yup.

In this article, we’ll look at how to add password strength validation with React, Formik and Yup.

How to add password strength validation with React, Formik and Yup?

To add password strength validation with React, Formik and Yup, we can use Yup’s matches method.

For instance, we write:

import React from "react";
import * as yup from "yup";
import { Formik, Field, Form } from "formik";

const schema = yup.object().shape({
  password: yup
    .string()
    .required("Please Enter your password")
    .matches(
      /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})/,
      "Must Contain 8 Characters, One Uppercase, One Lowercase, One Number and One Special Case Character"
    )
});

export default function App() {
  return (
    <div>
      <Formik
        initialValues={{
          password: ""
        }}
        validationSchema={schema}
        onSubmit={(values) => {
          console.log(values);
        }}
      >
        {({ errors, touched }) => (
          <Form>
            <Field name="password" type="password" />
            {errors.password && touched.password ? (
              <div>{errors.password}</div>
            ) : null}
            <button type="submit">Submit</button>
          </Form>
        )}
      </Formik>
    </div>
  );
}

We create the validation schema with yup.object().shape.

Then we calk yup.string().required to make the field with name password required.

And then we call matches with a regex to enforce the password strength.

Next, we add the Formik component with the validationSchema prop set to schema.

In the render prop function, we add the Field prop with the name prop set to 'password' to make it validate with the Yup password property.

If there’re errors, then we show errors.password property.

Conclusion

To add password strength validation with React, Formik and Yup, we can use Yup’s matches method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *