I have to use the react-password-checklist library to show the user if he is obeying the password rules declared in zod's schemaUser. However, I am not successful. obs: I'm using zod to validate the fields.
The password must have:
a minimum of 8 characters and a maximum of 32
must contain 1 uppercase letter
must contain 1 lowercase letter,
must contain 1 number
must contain 1 special character.
Rules and value props are mandatory in react-password-checklist. I managed to pass the value, however, the roles, I don't know how to pass because it comes from the zod.In rules i tryed userSchema.shape.password.refine.rules but the property 'shape' does not exist on type 'ZodEffects' I made the code below:
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>
);
};
Below is the schema with 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"
});
Links: