next.js 如何使用react-password-checklist与zod?

hvvq6cgz  于 2023-11-18  发布在  React
关注(0)|答案(1)|浏览(123)

我必须使用react-password-checklist库来显示用户是否遵守zod的schemaUser中声明的密码规则。但是,我没有成功。obs:我正在使用zod验证字段。
密码必须具有:

  • 最少8个字符,最多32个字符
  • 必须包含1个小写字母
  • 必须包含1个大写字母,
  • 必须包含1个数字
  • 必须包含1个特殊字符。

规则和值 prop 是强制性的react-password-checklist.我设法传递值,然而,角色,我不知道如何传递,因为它来自zod.在规则我尝试userSchema.shape.password.refine.rules但属性'shape'不存在类型'ZodEffects'我做了下面的代码:

import React from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import userSchema from '../../schema/signup';
import PasswordChecklist from "react-password-checklist"
import {
  Button,
  Flex,
  Text,
  FormControl,
  FormLabel,
  Heading,
  Input,
  Stack,
  FormErrorMessage
} from '@chakra-ui/react';
export const SignUp = () => {
  const {
    register,
    handleSubmit,
    getValues,
    formState: { errors, isValid }
  } = useForm<FormData>({
    resolver: zodResolver(userSchema)
  });
 return (
    <Stack minH={'100vh'} direction={{ base: 'column', lg: 'row' }}>
      <Flex p={8} flex={1} align={'center'} justify={'center'} bg="gray.300">
        <Stack spacing={4} w={'full'} maxW={'xl'}>
          <form onSubmit={handleSubmit(handleForm)}>
            <Heading fontSize={'2xl'}>Sign in to your account</Heading>
            <FormControl id="password" isInvalid={!!errors.password}>
              <FormLabel>Password</FormLabel>
              <Input
                type="password"
                {...register('password')}
                placeholder="Insert password"
              />
              <FormErrorMessage>{errors.password?.message}</FormErrorMessage>
              <PasswordChecklist value={getValues('password')} rules={userSchema.shape.password.refine.rules} />

            </FormControl>
            <FormControl
              id="confirm-password"
              isInvalid={!!errors.confirmPassword}
            >
              <FormLabel>Confirm password</FormLabel>
              <Input
                type="password"
                {...register('confirmPassword')}
                placeholder="Confirm password"
              />
              <FormErrorMessage>
                {errors.confirmPassword?.message}
              </FormErrorMessage>
            </FormControl>
              <Button
                colorScheme={'blue'}
                variant={'solid'}
                type="submit"
                disabled={isValid}
              >
                Sign in
              </Button>
            </Stack>
          </form>
        </Stack>
      </Flex>
    </Stack>
  );
};

字符串
下面是zod的模式。

const userSchema = z
   .object({
     password: z
       .string()
       .min(8, 'The password must be at least 8 characters long')
       .max(32, 'The password must be a maximun 32 characters')
       .regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%&*-])[A- Za-z\d!@#$%&*-]{8,}$/),
     confirmPassword: z.string(),
   .refine((fields) => fields.password === fields.confirmPassword, {
     path: ['confirmPassword'],
     message: "Passwords don't match"
   });


链接:
React Password Checklist
Zod

7qhs6swi

7qhs6swi1#

您需要创建自己的自定义验证。下面是我的示例。

const schema = z
  .object({
    email: z.string().email(),
    password: z.string().min(8),
  })
  .superRefine(({ password }, checkPassComplexity) => {
    const containsUppercase = (ch: string) => /[A-Z]/.test(ch);
    const containsLowercase = (ch: string) => /[a-z]/.test(ch);
    const containsSpecialChar = (ch: string) =>
      /[`!@#$%^&*()_\-+=\[\]{};':"\\|,.<>\/?~ ]/.test(ch);
    let countOfUpperCase = 0,
      countOfLowerCase = 0,
      countOfNumbers = 0,
      countOfSpecialChar = 0;
    for (let i = 0; i < password.length; i++) {
      let ch = password.charAt(i);
      if (!isNaN(+ch)) countOfNumbers++;
      else if (containsUppercase(ch)) countOfUpperCase++;
      else if (containsLowercase(ch)) countOfLowerCase++;
      else if (containsSpecialChar(ch)) countOfSpecialChar++;
    }
    if (
      countOfLowerCase < 1 ||
      countOfUpperCase < 1 ||
      countOfSpecialChar < 1 ||
      countOfNumbers < 1
    ) {
      checkPassComplexity.addIssue({
        code: "custom",
        message: "password does not meet complexity requirements",
      });
    }
  });

字符串

相关问题