Untitled

mail@pastecode.io avatar
unknown
tsx
2 months ago
2.3 kB
1
Indexable
Never
const formSchema = z.object({
  email: z
    .string()
    .min(1, '이메일을 입력해주세요')
    .email('유효한 이메일이 아닙니다.'),
  username: z
    .string()
    .min(3, '3글자 이상이어야 합니다.')
    .max(4, '4글자 이하입니다.'),
  password: z
    .string()
    .min(3, '8글자 이상이어야 합니다.')
    .max(8, '12글자 이하입니다.'),
});

type FormValuesKey = keyof FormValues;

const AuthForm: FC<{ signIn: (data: FormValues) => FormValues }> = ({
  signIn,
}) => {
  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      username: '',
      email: '',
      password: '',
    },
  });

  const onSubmit: SubmitHandler<FormValues> = async (data) => {
    const res = await signIn(data);
    console.log(res);
  };

  const formValuesKeys: FormValuesKey[] = ['email', 'password', 'username'];
  const fieldDetails: Record<
    keyof FormValues,
    { name: string; placeholder: string; description: string }
  > = {
    email: {
      name: '이메일',
      placeholder: '이메일을',
      description: '',
    },
    username: {
      name: '닉네임',
      placeholder: '닉네임을',
      description: '3글자 이상입니다.',
    },
    password: {
      name: '비밀번호',
      placeholder: '비밀번호를',
      description: '8글자 이상입니다.',
    },
  };

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className='w-1/4'>
        {formValuesKeys.map((formKey) => (
          <FormField
            key={formKey}
            control={form.control}
            name={formKey}
            render={({ field }) => (
              <FormItem>
                <FormLabel>{fieldDetails[formKey].name}</FormLabel>
                <FormControl>
                  <Input
                    placeholder={fieldDetails[formKey].placeholder}
                    {...field}
                  />
                </FormControl>
                <FormDescription>
                  {fieldDetails[formKey].description}
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
        ))}
        <Button type='submit'>회원가입</Button>
      </form>
    </Form>
  );
};

export default AuthForm;
Leave a Comment