我必须使用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"
});
1条答案
按热度按时间7qhs6swi1#
您需要创建自己的自定义验证。下面是我的示例。
字符串