1

How to create optional value with Tanstack form and Zod?

<script setup lang="ts">
    import { useI18n } from 'vue-i18n';
    import { z } from 'zod';
    import { revalidateLogic, useForm } from '@tanstack/vue-form';
    import { tWithJosa } from '@/utils/i18nJosa.ts';

    const { t } = useI18n({ useScope: 'global' });

    const schema = z.object({
        cover_letter: z
            .string()
            .trim()
            .nonempty({
                message: t('common.form.required_value', {
                    what: tWithJosa('recruit.cover_letter.label', '을/를'),
                }),
            })
            .max(1500, { message: t('common.form.max_notice', { count: 1500 }) }),
        attachments: z.array(z.file()).optional(),
        agreements: z.array(z.boolean()).refine((agreements) => agreements.length > 0, {
            message: t('common.form.agree_notice'),
        }),
    });

    const form = useForm({
        defaultValues: {
            cover_letter: '',
            attachments: [],
            agreements: [],
        },
        validationLogic: revalidateLogic(),
        validators: {
            onDynamic: schema,
        },
        onSubmit: ({ value }) => {
            console.log(value);
        },
    });
</script>

There is an error when registering validators(onDynamic).

I think it's a type mismatch problem, but I'm not sure.

enter image description here

1
  • Do you see the never[] on attachments and agreements? Looks like the tanstack forms useForm is not correctly inferring the types. Have you tried passing the expected type arguments explicitly? My best guess is that useForm is inferring the type of your formdata from defaultValues which then won't match up with your zod validator. Commented Nov 13 at 14:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.