nuxt / ui

A UI Library for Modern Web Apps, powered by Vue & Tailwind CSS.
https://ui.nuxt.com
MIT License
3.4k stars 374 forks source link

Zod Validation for nested object & Input error #1726

Closed a7med-hussien closed 3 weeks ago

a7med-hussien commented 3 weeks ago

Environment

<script setup lang="ts">
import { z } from 'zod'
import type { FormSubmitEvent } from '#ui/types'

const schema = z.object({
  user: z.object({
    email: z.string().email('Invalid email'),
    password: z.string().min(8, 'Must be at least 8 characters'),
  }),
})

type Schema = z.output<typeof schema>

const state = reactive({
  user: {
    email: undefined,
    password: undefined,
  },
})

async function onSubmit(event: FormSubmitEvent<Schema>) {
  // Do something with data
  console.log(event.data)
}
</script>

<template>
  <UForm :schema="schema" :state="state" class="space-y-4" @submit="onSubmit">
    <UFormGroup label="Email" name="email">
      <UInput v-model="state.user.email" />
    </UFormGroup>

    <UFormGroup label="Password" name="password">
      <UInput v-model="state.user.password" type="password" />
    </UFormGroup>

    <UButton type="submit">
      Submit
    </UButton>
  </UForm>
</template>

when I write schema like this

const schema = z.object({
  user: z.object({
    email: z.string().email('Invalid email'),
    password: z.string().min(8, 'Must be at least 8 characters'),
  }),
})

input validation & onSubmit method doesn't fire

but when I change it to

const schema = z.object({
    email: z.string().email('Invalid email'),
    password: z.string().min(8, 'Must be at least 8 characters'),
})

it works fine, but we need it with nested objects like this

const schema = z.object({
  user: z.object({
    email: z.string().email('Invalid email'),
    password: z.string().min(8, 'Must be at least 8 characters'),
  }),
})

Version

^2.13.0

Reproduction

https://stackblitz.com/edit/nuxt-ui-7rd9v1?file=app.vue

Description

nested objects validation not working and causing that onSubmit method not to work

Additional context

No response

Logs

No response

benjamincanac commented 3 weeks ago

Have you checked https://github.com/nuxt/ui/issues/1517?