首页 > 解决方案 > 如果密码包含数字,如何通过 React Hook Form 检查?

问题描述

我如何通过 React Hook Form 和 Yup 检查密码是否包含数字、大写字母和特殊符号?我在下面尝试了类似的方法,使用验证功能,但它不能正常工作。我有一个错误'无法读取未定义的属性'reduce''。

const Register = ({ setRegisterView }) => {
  const validationSchema = Yup.object().shape({
    email: Yup.string()
      .required("It is required.")
      .email("Email is wrong"),
    password: Yup.string()
      .required("It is required.")
      .min(8, "Password need to has 8 signs.")
.validate((value) => {
        return (
          [/[a-z]/, /[A-Z]/, /[0-9]/, /[^a-zA-Z0-9]/].every((pattern) =>
            pattern.test(value)
          ) ||
          "Information"
        );
      }),
});

  const {
    register: validate,
    formState: { errors },
    handleSubmit,
  } = useForm({ mode: "onSubmit", resolver: yupResolver(validationSchema) });

  return (
    <Wrapper>
      <Form onSubmit={handleSubmit(registerProcess)}>
        <FieldType>Email</FieldType>
        <StyledInput
          name="email"
          type="email"
          error={errors.email}
          {...validate("email")}
        />
        {errors.email && <Error>{errors.email.message}</Error>}
        <FieldType>Password</FieldType>
        <StyledInput
          name="password"
          type="password"
          error={errors.password}
          {...validate("password")}
        />
        {errors.password && <Error>{errors.password.message}</Error>}
        <LoginButton type="submit">SIGN UP</LoginButton>
      </Form>
    </Wrapper>
  );
};

export default Register;

标签: javascriptreactjsformsreact-hook-form

解决方案


我认为问题在于您正在使用validatewhich 期望 aPromise作为返回值 -> Docs。您应该改为test在此处使用。

const validationSchema = Yup.object().shape({
    email: Yup.string().required("It is required.").email("Email is wrong"),
    password: Yup.string()
      .required("It is required.")
      .min(8, "Password need to has 8 signs.")
      .test("passwordRequirements", "Information", (value) =>
        [/[a-z]/, /[A-Z]/, /[0-9]/, /[^a-zA-Z0-9]/].every((pattern) =>
          pattern.test(value)
        )
      )
  });

编辑 React Hook 表单 - FieldsArray - 是的验证 - 最小长度(分叉)


推荐阅读