使用React进行Formik,Yup密码强度验证 [英] Formik, Yup Password Strength Validation with React

查看:69
本文介绍了使用React进行Formik,Yup密码强度验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对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.

我正在使用Formik和Yup进行验证,但是遇到错误,当我在密码"字段中键入内容时,长度函数被调用的属性未定义.

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.

在yup中有一个名为"matches"的函数,我正在尝试使用该函数来检查正则表达式.那是我收到此错误的时间.我删除了此验证,然后将其他验证设置为密码字段即可正常工作.

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.

下面是SignUp.js文件的代码:-

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;

这是Chrome控制台中的错误:-

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

推荐答案

您需要将实际的RegExp对象传递给 matches ,而不是字符串.只需在密码架构中用双斜杠替换双引号即可:

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:

password: yup
    .string()
    .required('Please Enter your password')
    .matches(
      /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/,
      "Must Contain 8 Characters, One Uppercase, One Lowercase, One Number and one special case Character"
    ),

这篇关于使用React进行Formik,Yup密码强度验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆