nuxt / ui

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

Inconsistent UForm Schema Validation (Zod) #1268

Closed Hrdtr closed 7 months ago

Hrdtr commented 9 months ago

Environment

Version

^2.12.3

Reproduction

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

Description

const schema = z.object({
  identity: z.string(),
  password: z.string(),
})
type Schema = z.output<typeof schema>

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

At initial load, the form correctly throw an error because both identity & password field required. Then I input some text to the required field, the error is gone, which is expected. But the problem is, when I clear the field value again, it will no longer throw required error.

I have tried to change validateOn prop to other options, but got no luck

Additional context

-

Logs

-
Hrdtr commented 9 months ago

The initial state is undefined, then if we make the field state dirty then clearing the value, resulting the value to be an empty string. That's why zod getErrors() doesn't catch the error as it not 'undefined' anymore

What can users do when in this situation?

benjamincanac commented 9 months ago

Can you not initialize your form with empty strings?

reinventit commented 9 months ago

I think the problem you're seeing is that an empty string (after clearing the field) is still considered a string by Zod. If you want to make a value required in Zod you should use:

const schema = z.object({
  identity: z.string().min(1),
  password: z.string().min(1),
})

On top of that, it would probably be best to initialize with empty strings as @benjamincanac suggested.

Hrdtr commented 8 months ago

Okay, the problem is clear, Zod and the others here are acting as schema validators that are not form specific. However, it would be better if there was a note in the documentation regarding this, so that users do not expect that this integration will create similar behavior to libraries specifically for validating forms such as vee-validate What do you think? @benjamincanac

benjamincanac commented 8 months ago

@romhml Any feedback on this?

romhml commented 8 months ago

Nothing to add, @reinventit's response is correct, Zod handles all the validation logic in this scenario. I'll look into updating the docs to clarify this.

lammerfalcon commented 8 months ago

yeah, get this misunderstanding too, decide to switch to yup schema - zod schema mostly perefered on backend, on frontend its works in not what you expect way