Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formik, Yup Password Strength Validation with React

I am fairly new to React, and i have a sign up page where i have a password field to be validated with a Regex.

I am using Formik and Yup for validations, but i have encountered an error where it says the property where the length function is being called is undefined when i type in the "password" field.

There is a function called "matches" in yup, which i am trying to utilize for checking a regex. That is when i get this error. I removed this validation, after which other validations set to password field worked fine.

Below is the code for the SignUp.js file :-

import React from "react";
import Button from "react-bootstrap/Button";
import Form from "react-bootstrap/Form";
import "./SignUp.css";
import * as yup from "yup";
import { Formik } from "formik";

const schema = yup.object({
  username: yup.string().required('Please Enter a username'),
  email: yup
    .string()
    .email()
    .required('Please Enter your Email'),
  confirmEmail: yup
    .string()
    .email()
    .required()
    .oneOf([yup.ref("email"), null], "Emails must match"),
  password: yup
    .string()
    .required('Please Enter your password')
    .matches(
      "^(?=.*[A-Za-z])(?=.*d)(?=.*[@$!%*#?&])[A-Za-zd@$!%*#?&]{8,}$",
      "Must Contain 8 Characters, One Uppercase, One Lowercase, One Number and one special case Character"
    ),
  confirmPassword: yup
    .string()
    .required()
    .oneOf([yup.ref("password"), null], "Passwords must match")
});

const SignUp = props => {
  return (
    <Formik
    validationSchema={schema}
    onSubmit={console.log}
    initialValues={{
      username: "",
      email : "",
      confirmEmail : "",
      password: "",
      confirmPassword : ""
    }}
  >
  {({
    handleSubmit,
    handleChange,
    handleBlur,
    values,
    touched,
    isValid,
    errors,
  }) => (
    <div className="SignUpForm">
      <h1 className="SignInHeading">SIGN UP</h1>
      <Form noValidate onSubmit={handleSubmit}>
        <Form.Group controlId="formBasicUserName">
          <Form.Control
            size="lg"
            className="SignUpFormControls"
            type="text"
            name="username"
            value={values.username}
            onChange={handleChange}
            placeholder="Username"
            isInvalid={!!errors.username}
          />
          <Form.Control.Feedback className="FeedBack" type="invalid">
          {errors.username}
        </Form.Control.Feedback>
        </Form.Group>

        <Form.Group controlId="formBasicEmail">
          <Form.Control
            type="email"
            placeholder="Email"
            value={values.email}
            onChange={handleChange}
            name="email"
            className="SignUpFormControls"
            size="lg"
            isInvalid={!!errors.email}
          />
          <Form.Control.Feedback className="FeedBack" type="invalid">
          {errors.email}
        </Form.Control.Feedback>
        </Form.Group>

        <Form.Group controlId="formBasicConfirmEmail">
          <Form.Control
            type="email"
            className="SignUpFormControls"
            size="lg"
            name="confirmEmail"
            value = {values.confirmEmail}
            onChange={handleChange}
            placeholder="Confirm Email"
            isInvalid={!!errors.confirmEmail}
          />
          <Form.Control.Feedback className="FeedBack" type="invalid">
          {errors.confirmEmail}
        </Form.Control.Feedback>
        </Form.Group>

        <Form.Group controlId="formBasicPassword">
          <Form.Control
            className="SignUpFormControls"
            size="lg"
            type="password"
            name="password"
            value={values.password}
            onChange={handleChange}
            placeholder="Password"
            isInvalid={!!errors.password}
          />
          <Form.Control.Feedback className="FeedBack" type="invalid">
          {errors.password}
        </Form.Control.Feedback>
        </Form.Group>

        <Form.Group controlId="formBasicConfirmPassword">
          <Form.Control
            className="SignUpFormControls"
            size="lg"
            name="confirmPassword"
            onChange={handleChange}
            type="password"
            value={values.confirmPassword}
            placeholder="Confirm Password"
            isInvalid={!!errors.confirmPassword}
          /><Form.Control.Feedback className="FeedBack" type="invalid">
          {errors.confirmPassword}
        </Form.Control.Feedback>
        </Form.Group>

        <Button variant="primary" className="SignUpButton" type="submit">
          Sign Up
        </Button>
        <Form.Text>
          Already a User?{" "}
          <a href="#signin" onClick={props.toggle}>
            Sign In
          </a>
        </Form.Text>
      </Form>
    </div>)}
    </Formik>
  );
};

export default SignUp;

Here is the error in chrome console :-

formik.esm.js:721 Uncaught (in promise) TypeError: Cannot read property 'length' of undefined
    at yupToFormErrors (formik.esm.js:721)
    at formik.esm.js:276
like image 622
Shashaank V V Avatar asked Apr 01 '19 08:04

Shashaank V V


4 Answers

You need to pass an actual RegExp object to matches, not a string. Just replace the double quotes with forward slashes in your password schema:

EDIT: Updated to use regex from @Bren

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"
    ),
like image 112
Daniel M. Avatar answered Oct 18 '22 16:10

Daniel M.


This is what I finally got to work.

 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"
          ),

I took this regex string from this article: https://www.thepolyglotdeveloper.com/2015/05/use-regex-to-test-password-strength-in-javascript/

like image 25
Bren Avatar answered Oct 18 '22 17:10

Bren


Okay, after a couple of hours of tinkering around, i decided to do my own custom validation instead.

Here is what i did :-

password: yup
    .string()
    .required("Please Enter your password")
    .test(
      "regex",
      "Password must be min 8 characters, and have 1 Special Character, 1 Uppercase, 1 Number and 1 Lowercase",
      val => {
        let regExp = new RegExp(
          "^(?=.*\\d)(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z]).{8,}$"
        );
        console.log(regExp.test(val), regExp, val);
        return regExp.test(val);
      }
    )

For now, this is working fine. But i would really like to know why the error is popping up. Please post it as an answer if you are able to find a solution, and if it works for me i will mark it as the right answer. Thanks.

like image 6
Shashaank V V Avatar answered Oct 18 '22 17:10

Shashaank V V


Came across this last night trying to solve a similar React+Formik+Yup password validation issue. Overall, the solutions here are good. I only comment to offer a slightly different regular expression:

/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$/

This differs in the fourth look-ahead. In this version, it looks for anything that is not a letter or digit. The previous REs all limited the definition of "special character" to 8 or so specific characters. This will match a wider range.

I had initially used (?=.*[^\w]), which negates the "word" class (\w), but that class includes the underscore. So doing it that way would not count the underscore as a special character.

like image 3
rjray Avatar answered Oct 18 '22 16:10

rjray