mirror of
https://github.com/ArthurDanjou/ui.git
synced 2026-01-14 12:14:41 +01:00
feat(Form): nested form validation (#23)
Co-authored-by: Benjamin Canac <canacb1@gmail.com>
This commit is contained in:
66
playground/components/FormNestedExample.vue
Normal file
66
playground/components/FormNestedExample.vue
Normal file
@@ -0,0 +1,66 @@
|
||||
<script setup lang="ts">
|
||||
import { z } from 'zod'
|
||||
import type { FormSubmitEvent } from '#ui/types/form'
|
||||
|
||||
const schema = z.object({
|
||||
email: z.string().min(2),
|
||||
password: z.string().min(8)
|
||||
})
|
||||
|
||||
type Schema = z.output<typeof schema>
|
||||
|
||||
const nestedSchema = z.object({
|
||||
phone: z.string().length(10)
|
||||
})
|
||||
|
||||
type NestedSchema = z.output<typeof nestedSchema>
|
||||
|
||||
const state = reactive<Partial<Schema & { nested: Partial<NestedSchema> }>>({
|
||||
nested: {}
|
||||
})
|
||||
|
||||
const checked = ref(false)
|
||||
|
||||
function onSubmit (event: FormSubmitEvent<Schema>) {
|
||||
console.log('Success', event.data)
|
||||
}
|
||||
|
||||
function onError (event: any) {
|
||||
console.log('Error', event)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UForm
|
||||
:state="state"
|
||||
:schema="schema"
|
||||
class="gap-4 flex flex-col w-60"
|
||||
@submit="(event) => onSubmit(event)"
|
||||
@error="(event) => onError(event)"
|
||||
>
|
||||
<UFormField label="Email" name="email">
|
||||
<UInput v-model="state.email" placeholder="john@lennon.com" />
|
||||
</UFormField>
|
||||
|
||||
<UFormField label="Password" name="password">
|
||||
<UInput v-model="state.password" type="password" />
|
||||
</UFormField>
|
||||
|
||||
<div>
|
||||
<input id="check" v-model="checked" type="checkbox" name="check" @change="state.nested = {}">
|
||||
<label for="check"> Check me </label>
|
||||
</div>
|
||||
|
||||
<UForm v-if="checked && state.nested" :state="state.nested" :schema="nestedSchema">
|
||||
<UFormField label="Phone" name="phone">
|
||||
<UInput v-model="state.nested.phone" />
|
||||
</UFormField>
|
||||
</UForm>
|
||||
|
||||
<div>
|
||||
<UButton color="gray" type="submit">
|
||||
Submit
|
||||
</UButton>
|
||||
</div>
|
||||
</UForm>
|
||||
</template>
|
||||
85
playground/components/FormNestedListExample.vue
Normal file
85
playground/components/FormNestedListExample.vue
Normal file
@@ -0,0 +1,85 @@
|
||||
<script setup lang="ts">
|
||||
import { z } from 'zod'
|
||||
import type { FormSubmitEvent } from '#ui/types/form'
|
||||
|
||||
const schema = z.object({
|
||||
email: z.string().min(2),
|
||||
password: z.string().min(8)
|
||||
})
|
||||
|
||||
type Schema = z.output<typeof schema>
|
||||
|
||||
const itemSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
price: z.string().min(1)
|
||||
})
|
||||
|
||||
type ItemSchema = z.output<typeof itemSchema>
|
||||
|
||||
const state = reactive<Partial<Schema & { items: Partial<ItemSchema>[] }>>({})
|
||||
|
||||
function addItem () {
|
||||
if (!state.items) {
|
||||
state.items = []
|
||||
}
|
||||
state.items.push({})
|
||||
}
|
||||
|
||||
function removeItem () {
|
||||
if (state.items) {
|
||||
state.items.pop()
|
||||
}
|
||||
}
|
||||
const formItemRef = ref()
|
||||
|
||||
function onSubmit (event: FormSubmitEvent<Schema>) {
|
||||
console.log('Success', event.data)
|
||||
}
|
||||
|
||||
function onError (event: any) {
|
||||
console.log('Error', event)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UForm
|
||||
ref="formItemRef"
|
||||
:state="state"
|
||||
:schema="schema"
|
||||
class="gap-4 flex flex-col w-60"
|
||||
@submit="onSubmit"
|
||||
@error="onError"
|
||||
>
|
||||
<UFormField label="Email" name="email">
|
||||
<UInput v-model="state.email" placeholder="john@lennon.com" />
|
||||
</UFormField>
|
||||
|
||||
<UFormField label="Password" name="password">
|
||||
<UInput v-model="state.password" type="password" />
|
||||
</UFormField>
|
||||
|
||||
<UForm v-for="item, count in state.items" :key="count" :state="item" :schema="itemSchema" class="flex gap-2">
|
||||
<UFormField label="Name" name="name">
|
||||
<UInput v-model="item.name" />
|
||||
</UFormField>
|
||||
<UFormField label="Price" name="price">
|
||||
<UInput v-model="item.price" />
|
||||
</UFormField>
|
||||
</UForm>
|
||||
|
||||
<div class="flex gap-2">
|
||||
<UButton color="black" @click="addItem()">
|
||||
Add Item
|
||||
</UButton>
|
||||
|
||||
<UButton color="black" variant="ghost" @click="removeItem()">
|
||||
Remove Item
|
||||
</UButton>
|
||||
</div>
|
||||
<div>
|
||||
<UButton color="gray" type="submit">
|
||||
Submit
|
||||
</UButton>
|
||||
</div>
|
||||
</UForm>
|
||||
</template>
|
||||
@@ -24,81 +24,88 @@ function onSubmit (event: FormSubmitEvent<User>) {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex gap-4">
|
||||
<UForm
|
||||
:state="state"
|
||||
:schema="schema"
|
||||
class="gap-4 flex flex-col w-60"
|
||||
@submit="(event) => onSubmit(event)"
|
||||
>
|
||||
<UFormField label="Email" name="email">
|
||||
<UInput v-model="state.email" placeholder="john@lennon.com" />
|
||||
</UFormField>
|
||||
|
||||
<UFormField label="Password" name="password">
|
||||
<UInput v-model="state.password" type="password" />
|
||||
</UFormField>
|
||||
|
||||
<div>
|
||||
<UButton color="gray" type="submit">
|
||||
Submit
|
||||
</UButton>
|
||||
</div>
|
||||
</UForm>
|
||||
|
||||
<UForm
|
||||
:state="state2"
|
||||
:schema="schema"
|
||||
class="gap-4 flex flex-col w-60"
|
||||
:validate-on-input-delay="2000"
|
||||
@submit="(event) => onSubmit(event)"
|
||||
>
|
||||
<UFormField label="Email" name="email">
|
||||
<UInput v-model="state2.email" placeholder="john@lennon.com" />
|
||||
</UFormField>
|
||||
|
||||
<UFormField
|
||||
label="Password"
|
||||
name="password"
|
||||
:validate-on-input-delay="50"
|
||||
eager-validation
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="flex gap-4">
|
||||
<UForm
|
||||
:state="state"
|
||||
:schema="schema"
|
||||
class="gap-4 flex flex-col w-60"
|
||||
@submit="(event) => onSubmit(event)"
|
||||
>
|
||||
<UInput v-model="state2.password" type="password" />
|
||||
</UFormField>
|
||||
<UFormField label="Email" name="email">
|
||||
<UInput v-model="state.email" placeholder="john@lennon.com" />
|
||||
</UFormField>
|
||||
|
||||
<div>
|
||||
<UButton color="gray" type="submit">
|
||||
Submit
|
||||
</UButton>
|
||||
</div>
|
||||
</UForm>
|
||||
<UFormField label="Password" name="password">
|
||||
<UInput v-model="state.password" type="password" />
|
||||
</UFormField>
|
||||
|
||||
<UForm
|
||||
ref="disabledForm"
|
||||
:state="state3"
|
||||
:schema="schema"
|
||||
class="gap-4 flex flex-col w-60"
|
||||
disabled
|
||||
@submit="(event) => onSubmit(event)"
|
||||
>
|
||||
<UFormField label="Email" name="email">
|
||||
<UInput v-model="state2.email" placeholder="john@lennon.com" />
|
||||
</UFormField>
|
||||
<div>
|
||||
<UButton color="gray" type="submit">
|
||||
Submit
|
||||
</UButton>
|
||||
</div>
|
||||
</UForm>
|
||||
|
||||
<UFormField
|
||||
label="Password"
|
||||
name="password"
|
||||
:validate-on-input-delay="50"
|
||||
eager-validation
|
||||
<UForm
|
||||
:state="state2"
|
||||
:schema="schema"
|
||||
class="gap-4 flex flex-col w-60"
|
||||
:validate-on-input-delay="2000"
|
||||
@submit="(event) => onSubmit(event)"
|
||||
>
|
||||
<UInput v-model="state2.password" type="password" />
|
||||
</UFormField>
|
||||
<UFormField label="Email" name="email">
|
||||
<UInput v-model="state2.email" placeholder="john@lennon.com" />
|
||||
</UFormField>
|
||||
|
||||
<div>
|
||||
<UButton color="gray" type="submit" :disabled="disabledForm?.disabled">
|
||||
Submit
|
||||
</UButton>
|
||||
</div>
|
||||
</UForm>
|
||||
<UFormField
|
||||
label="Password"
|
||||
name="password"
|
||||
:validate-on-input-delay="50"
|
||||
eager-validation
|
||||
>
|
||||
<UInput v-model="state2.password" type="password" />
|
||||
</UFormField>
|
||||
|
||||
<div>
|
||||
<UButton color="gray" type="submit">
|
||||
Submit
|
||||
</UButton>
|
||||
</div>
|
||||
</UForm>
|
||||
|
||||
<UForm
|
||||
ref="disabledForm"
|
||||
:state="state3"
|
||||
:schema="schema"
|
||||
class="gap-4 flex flex-col w-60"
|
||||
disabled
|
||||
@submit="(event) => onSubmit(event)"
|
||||
>
|
||||
<UFormField label="Email" name="email">
|
||||
<UInput v-model="state3.email" placeholder="john@lennon.com" />
|
||||
</UFormField>
|
||||
|
||||
<UFormField
|
||||
label="Password"
|
||||
name="password"
|
||||
:validate-on-input-delay="50"
|
||||
eager-validation
|
||||
>
|
||||
<UInput v-model="state3.password" type="password" />
|
||||
</UFormField>
|
||||
|
||||
<div>
|
||||
<UButton color="gray" type="submit" :disabled="disabledForm?.disabled">
|
||||
Submit
|
||||
</UButton>
|
||||
</div>
|
||||
</UForm>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-4">
|
||||
<FormNestedExample />
|
||||
<FormNestedListExample />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -4,13 +4,14 @@ import type { AppConfig } from '@nuxt/schema'
|
||||
import _appConfig from '#build/app.config'
|
||||
import theme from '#build/ui/form'
|
||||
import { getYupErrors, isYupSchema, getValibotError, isValibotSchema, getZodErrors, isZodSchema, getJoiErrors, isJoiSchema } from '../utils/form'
|
||||
import type { FormSchema, FormError, FormInputEvents, FormErrorEvent, FormSubmitEvent, FormEvent, InjectedFormOptions, Form } from '../types/form'
|
||||
import type { FormSchema, FormError, FormInputEvents, FormErrorEvent, FormSubmitEvent, FormEvent, FormInjectedOptions, Form, FormErrorWithId } from '../types/form'
|
||||
|
||||
const appConfig = _appConfig as AppConfig & { ui: { form: Partial<typeof theme> } }
|
||||
|
||||
const form = tv({ extend: tv(theme), ...(appConfig.ui?.form || {}) })
|
||||
|
||||
export interface FormProps<T extends object> {
|
||||
id?: string | number
|
||||
schema?: FormSchema<T>
|
||||
state: Partial<T>
|
||||
validate?: (state: Partial<T>) => Promise<FormError[] | void>
|
||||
@@ -29,18 +30,24 @@ export interface FormSlots {
|
||||
default(): any
|
||||
}
|
||||
|
||||
export class FormException extends Error {
|
||||
constructor (message: string) {
|
||||
super(message)
|
||||
this.message = message
|
||||
Object.setPrototypeOf(this, FormException.prototype)
|
||||
export class FormValidationException extends Error {
|
||||
formId: string | number
|
||||
errors: FormErrorWithId[]
|
||||
childrens: FormValidationException[]
|
||||
|
||||
constructor (formId: string | number, errors: FormErrorWithId[], childErrors: FormValidationException[]) {
|
||||
super('Form validation exception')
|
||||
this.formId = formId
|
||||
this.errors = errors
|
||||
this.childrens = childErrors
|
||||
Object.setPrototypeOf(this, FormValidationException.prototype)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<script lang="ts" setup generic="T extends object">
|
||||
import { provide, ref, onUnmounted, onMounted, computed } from 'vue'
|
||||
import { useEventBus } from '@vueuse/core'
|
||||
import { provide, inject, nextTick, ref, onUnmounted, onMounted, computed } from 'vue'
|
||||
import { useEventBus, type UseEventBusReturn } from '@vueuse/core'
|
||||
import { useId } from '#imports'
|
||||
|
||||
const props = withDefaults(defineProps<FormProps<T>>(), {
|
||||
@@ -52,16 +59,26 @@ const props = withDefaults(defineProps<FormProps<T>>(), {
|
||||
const emit = defineEmits<FormEmits<T>>()
|
||||
defineSlots<FormSlots>()
|
||||
|
||||
const formId = useId()
|
||||
const bus = useEventBus<FormEvent>(`form-${formId}`)
|
||||
const formId = props.id ?? useId()
|
||||
|
||||
onMounted(() => {
|
||||
const bus = useEventBus<FormEvent>(`form-${formId}`)
|
||||
const parentBus = inject<UseEventBusReturn<FormEvent, string> | undefined>(
|
||||
'form-events',
|
||||
undefined
|
||||
)
|
||||
provide('form-events', bus)
|
||||
|
||||
|
||||
const nestedForms = ref<Map<string | number, { validate: () => any }>>(new Map())
|
||||
|
||||
onMounted(async () => {
|
||||
bus.on(async (event) => {
|
||||
if (
|
||||
event.type !== 'submit' &&
|
||||
props.validateOn?.includes(event.type as FormInputEvents)
|
||||
) {
|
||||
await _validate(event.name, { silent: true })
|
||||
if (event.type === 'attach') {
|
||||
nestedForms.value.set(event.formId, { validate: event.validate })
|
||||
} else if (event.type === 'detach') {
|
||||
nestedForms.value.delete(event.formId)
|
||||
} else if (props.validateOn?.includes(event.type as FormInputEvents)) {
|
||||
await _validate({ name: event.name, silent: true, nested: false })
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -70,20 +87,40 @@ onUnmounted(() => {
|
||||
bus.reset()
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
if (parentBus) {
|
||||
await nextTick()
|
||||
parentBus.emit({ type: 'attach', validate: _validate, formId })
|
||||
}
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
if (parentBus) {
|
||||
parentBus.emit({ type: 'detach', formId })
|
||||
}
|
||||
})
|
||||
|
||||
const options = {
|
||||
disabled: computed(() => props.disabled),
|
||||
validateOnInputDelay: computed(() => props.validateOnInputDelay)
|
||||
}
|
||||
provide<InjectedFormOptions>('form-options', options)
|
||||
provide<FormInjectedOptions>('form-options', options)
|
||||
|
||||
const errors = ref<FormError[]>([])
|
||||
const errors = ref<FormErrorWithId[]>([])
|
||||
provide('form-errors', errors)
|
||||
provide('form-events', bus)
|
||||
|
||||
const inputs = ref<Record<string, string>>({})
|
||||
provide('form-inputs', inputs)
|
||||
function resolveErrorIds (errs: FormError[]): FormErrorWithId[] {
|
||||
return errs.map((err) => ({
|
||||
...err,
|
||||
id: inputs.value[err.name]
|
||||
}))
|
||||
}
|
||||
|
||||
async function getErrors (): Promise<FormError[]> {
|
||||
async function getErrors (): Promise<FormErrorWithId[]> {
|
||||
let errs = props.validate ? (await props.validate(props.state)) ?? [] : []
|
||||
|
||||
if (props.schema) {
|
||||
if (isZodSchema(props.schema)) {
|
||||
errs = errs.concat(await getZodErrors(props.state, props.schema))
|
||||
@@ -98,34 +135,39 @@ async function getErrors (): Promise<FormError[]> {
|
||||
}
|
||||
}
|
||||
|
||||
return errs
|
||||
return resolveErrorIds(errs)
|
||||
}
|
||||
|
||||
async function _validate (
|
||||
name?: string | string[],
|
||||
opts: { silent?: boolean } = { silent: false }
|
||||
opts: { name?: string | string[], silent?: boolean, nested?: boolean } = { silent: false, nested: true }
|
||||
): Promise<T | false> {
|
||||
let paths = name
|
||||
if (name && !Array.isArray(name)) {
|
||||
paths = [name]
|
||||
}
|
||||
const names = opts.name && !Array.isArray(opts.name) ? [opts.name] : opts.name
|
||||
|
||||
if (paths) {
|
||||
const nestedValidatePromises = !names && opts.nested ? Array.from(nestedForms.value.values()).map(
|
||||
({ validate }) => validate().then(() => undefined).catch((error: Error) => {
|
||||
if (!(error instanceof FormValidationException)) {
|
||||
throw error
|
||||
}
|
||||
return error
|
||||
})
|
||||
) : []
|
||||
|
||||
if (names) {
|
||||
const otherErrors = errors.value.filter(
|
||||
(error) => !paths!.includes(error.name)
|
||||
(error) => !names!.includes(error.name)
|
||||
)
|
||||
const pathErrors = (await getErrors()).filter((error) =>
|
||||
paths!.includes(error.name)
|
||||
names!.includes(error.name)
|
||||
)
|
||||
errors.value = otherErrors.concat(pathErrors)
|
||||
} else {
|
||||
errors.value = await getErrors()
|
||||
}
|
||||
|
||||
if (errors.value.length > 0) {
|
||||
const childErrors = nestedValidatePromises ? await Promise.all(nestedValidatePromises) : []
|
||||
if (errors.value.length + childErrors.length > 0) {
|
||||
if (opts.silent) return false
|
||||
|
||||
throw new FormException(`Form validation failed: ${JSON.stringify(errors.value, null, 2)}`)
|
||||
throw new FormValidationException(formId, errors.value, childErrors)
|
||||
}
|
||||
|
||||
return props.state as T
|
||||
@@ -133,25 +175,26 @@ async function _validate (
|
||||
|
||||
async function onSubmit (payload: Event) {
|
||||
const event = payload as SubmitEvent
|
||||
|
||||
try {
|
||||
await _validate()
|
||||
await _validate({ nested: true })
|
||||
const submitEvent: FormSubmitEvent<any> = {
|
||||
...event,
|
||||
data: props.state
|
||||
}
|
||||
emit('submit', submitEvent)
|
||||
|
||||
} catch (error) {
|
||||
if (!(error instanceof FormException)) {
|
||||
if (!(error instanceof FormValidationException)) {
|
||||
throw error
|
||||
}
|
||||
|
||||
const errorEvent: FormErrorEvent = {
|
||||
...event,
|
||||
errors: errors.value.map((err) => ({
|
||||
...err,
|
||||
id: inputs.value[err.name]
|
||||
}))
|
||||
errors: error.errors,
|
||||
childrens: error.childrens
|
||||
}
|
||||
|
||||
emit('error', errorEvent)
|
||||
}
|
||||
}
|
||||
@@ -159,25 +202,28 @@ async function onSubmit (payload: Event) {
|
||||
defineExpose<Form<T>>({
|
||||
validate: _validate,
|
||||
errors,
|
||||
|
||||
setErrors (errs: FormError[], name?: string) {
|
||||
errors.value = errs
|
||||
if (name) {
|
||||
errors.value = errors.value
|
||||
.filter((error) => error.name !== name)
|
||||
.concat(errs)
|
||||
.concat(resolveErrorIds(errs))
|
||||
} else {
|
||||
errors.value = errs
|
||||
errors.value = resolveErrorIds(errs)
|
||||
}
|
||||
},
|
||||
|
||||
async submit () {
|
||||
await onSubmit(new Event('submit'))
|
||||
},
|
||||
|
||||
getErrors (name?: string) {
|
||||
if (name) {
|
||||
return errors.value.filter((err) => err.name === name)
|
||||
}
|
||||
return errors.value
|
||||
},
|
||||
|
||||
clear (name?: string) {
|
||||
if (name) {
|
||||
errors.value = errors.value.filter((err) => err.name !== name)
|
||||
@@ -190,7 +236,12 @@ defineExpose<Form<T>>({
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<form :class="form({ class: props.class })" @submit.prevent="onSubmit">
|
||||
<component
|
||||
:is="parentBus ? 'div' : 'form'"
|
||||
:id="formId"
|
||||
:class="form({ class: props.class })"
|
||||
@submit.prevent="onSubmit"
|
||||
>
|
||||
<slot />
|
||||
</form>
|
||||
</component>
|
||||
</template>
|
||||
|
||||
@@ -37,7 +37,7 @@ export interface FormFieldSlots {
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { computed, ref, inject, provide, type Ref } from 'vue'
|
||||
import type { FormError, InjectedFormFieldOptions } from '../types/form'
|
||||
import type { FormError, FormFieldInjectedOptions } from '../types/form'
|
||||
import { useId } from '#imports'
|
||||
|
||||
const props = defineProps<FormFieldProps>()
|
||||
@@ -59,7 +59,7 @@ const error = computed(() => {
|
||||
|
||||
const inputId = ref(useId())
|
||||
|
||||
provide<InjectedFormFieldOptions<FormFieldProps>>('form-field', {
|
||||
provide<FormFieldInjectedOptions<FormFieldProps>>('form-field', {
|
||||
error,
|
||||
inputId,
|
||||
name: computed(() => props.name),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { inject, ref, computed } from 'vue'
|
||||
import { type UseEventBusReturn, useDebounceFn } from '@vueuse/core'
|
||||
import type { FormEvent, FormInputEvents, InjectedFormFieldOptions, InjectedFormOptions } from '../types/form'
|
||||
import type { FormEvent, FormInputEvents, FormFieldInjectedOptions, FormInjectedOptions } from '../types/form'
|
||||
|
||||
type Props<T> = {
|
||||
id?: string
|
||||
@@ -15,9 +15,9 @@ type Props<T> = {
|
||||
}
|
||||
|
||||
export function useFormField <T> (inputProps?: Props<T>) {
|
||||
const formOptions = inject<InjectedFormOptions | undefined>('form-options', undefined)
|
||||
const formOptions = inject<FormInjectedOptions | undefined>('form-options', undefined)
|
||||
const formBus = inject<UseEventBusReturn<FormEvent, string> | undefined>('form-events', undefined)
|
||||
const formField = inject<InjectedFormFieldOptions<T> | undefined>('form-field', undefined)
|
||||
const formField = inject<FormFieldInjectedOptions<T> | undefined>('form-field', undefined)
|
||||
const formInputs = inject<any>('form-inputs', undefined)
|
||||
|
||||
if (formField) {
|
||||
|
||||
43
src/runtime/types/form.d.ts
vendored
43
src/runtime/types/form.d.ts
vendored
@@ -1,8 +1,7 @@
|
||||
import type { ComputedRef, Ref } from 'vue'
|
||||
|
||||
export interface Form<T> {
|
||||
validate (path?: string | string[], opts?: { silent?: true }): Promise<T | false>
|
||||
validate (path?: string | string[], opts?: { silent?: false }): Promise<T | false>
|
||||
validate (opts?: { name: string | string[], silent?: false, nested?: boolean }): Promise<T | false>
|
||||
clear (path?: string): void
|
||||
errors: Ref<FormError[]>
|
||||
setErrors (errs: FormError[], path?: string): void
|
||||
@@ -29,16 +28,43 @@ export interface FormErrorWithId extends FormError {
|
||||
}
|
||||
|
||||
export type FormSubmitEvent<T> = SubmitEvent & { data: T }
|
||||
export type FormErrorEvent = SubmitEvent & { errors: FormErrorWithId[] }
|
||||
|
||||
export type FormEventType = FormInputEvents | 'submit'
|
||||
export type FormValidationError = {
|
||||
errors: FormErrorWithId[]
|
||||
childrens: FormValidationError[]
|
||||
}
|
||||
|
||||
export interface FormEvent {
|
||||
export type FormErrorEvent = SubmitEvent & FormValidationError
|
||||
|
||||
export type FormEventType = FormInputEvents
|
||||
|
||||
export type FormChildAttachEvent = {
|
||||
type: 'attach'
|
||||
formId: string | number
|
||||
validate: Form<any>['validate']
|
||||
}
|
||||
|
||||
export type FormChildDetachEvent = {
|
||||
type: 'detach'
|
||||
formId: string | number
|
||||
}
|
||||
|
||||
export type FormInputEvent = {
|
||||
type: FormEventType
|
||||
name?: string
|
||||
}
|
||||
|
||||
export interface InjectedFormFieldOptions<T> {
|
||||
export type FormEvent =
|
||||
| FormInputEvent
|
||||
| FormChildAttachEvent
|
||||
| FormChildDetachEvent
|
||||
|
||||
export interface FormInjectedOptions {
|
||||
disabled?: ComputedRef<boolean>
|
||||
validateOnInputDelay?: ComputedRef<number>
|
||||
}
|
||||
|
||||
export interface FormFieldInjectedOptions<T> {
|
||||
inputId: Ref<string | undefined>
|
||||
name: ComputedRef<string | undefined>
|
||||
size: ComputedRef<T['size']>
|
||||
@@ -46,8 +72,3 @@ export interface InjectedFormFieldOptions<T> {
|
||||
eagerValidation: ComputedRef<boolean | undefined>
|
||||
validateOnInputDelay: ComputedRef<number | undefined>
|
||||
}
|
||||
|
||||
export interface InjectedFormOptions {
|
||||
disabled?: ComputedRef<boolean>
|
||||
validateOnInputDelay?: ComputedRef<number>
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { reactive } from 'vue'
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { reactive, ref, nextTick } from 'vue'
|
||||
import { describe, it, expect, test, beforeEach, vi } from 'vitest'
|
||||
import type { FormProps } from '../../src/runtime/components/Form.vue'
|
||||
import {
|
||||
UForm,
|
||||
@@ -49,6 +49,7 @@ async function renderForm (options: {
|
||||
const state = reactive({})
|
||||
return await mountSuspended(UForm, {
|
||||
props: {
|
||||
id: 42,
|
||||
state,
|
||||
...options.props
|
||||
},
|
||||
@@ -447,4 +448,233 @@ describe('Form', () => {
|
||||
await new Promise((r) => setTimeout(r, 50))
|
||||
expect(wrapper.text()).not.toContain('Error message')
|
||||
})
|
||||
|
||||
|
||||
describe('api', async () => {
|
||||
let wrapper: any
|
||||
let form: any
|
||||
let state: any
|
||||
|
||||
beforeEach(async () => {
|
||||
wrapper = await mountSuspended({
|
||||
components: {
|
||||
UFormField,
|
||||
UForm,
|
||||
UInput
|
||||
},
|
||||
setup () {
|
||||
const form = ref()
|
||||
const state = reactive({})
|
||||
const schema = z.object({
|
||||
email: z.string().email(),
|
||||
password: z.string().min(8)
|
||||
})
|
||||
|
||||
const onError = vi.fn()
|
||||
const onSubmit = vi.fn()
|
||||
|
||||
return { state, schema, form, onSubmit, onError }
|
||||
},
|
||||
template: `
|
||||
<UForm ref="form" :state="state" :schema="schema" @submit="onSubmit" @error="onError">
|
||||
<UFormField id="emailField" name="email">
|
||||
<UInput id="emailInput" v-model="state.email" />
|
||||
</UFormField>
|
||||
<UFormField id="passwordField" name="password">
|
||||
<UInput id="passwordInput" v-model="state.password" />
|
||||
</UFormField>
|
||||
</UForm>
|
||||
`
|
||||
})
|
||||
form = wrapper.setupState.form
|
||||
state = wrapper.setupState.state
|
||||
})
|
||||
|
||||
test('setErrors works', async () => {
|
||||
form.value.setErrors([{
|
||||
name: 'email',
|
||||
message: 'this is an error'
|
||||
}])
|
||||
|
||||
expect(form.value.errors).toMatchObject([{
|
||||
id: 'emailInput',
|
||||
name: 'email',
|
||||
message: 'this is an error'
|
||||
}])
|
||||
|
||||
await nextTick()
|
||||
|
||||
const emailField = wrapper.find('#emailField')
|
||||
expect(emailField.text()).toBe('this is an error')
|
||||
|
||||
const passwordField = wrapper.find('#passwordField')
|
||||
expect(passwordField.text()).toBe('')
|
||||
})
|
||||
|
||||
test('clear works', async () => {
|
||||
form.value.setErrors([{
|
||||
id: 'emailInput',
|
||||
name: 'email',
|
||||
message: 'this is an error'
|
||||
}])
|
||||
|
||||
form.value.clear()
|
||||
|
||||
expect(form.value.errors).toMatchObject([])
|
||||
|
||||
const emailField = wrapper.find('#emailField')
|
||||
expect(emailField.text()).toBe('')
|
||||
|
||||
const passwordField = wrapper.find('#passwordField')
|
||||
expect(passwordField.text()).toBe('')
|
||||
})
|
||||
|
||||
test('submit error works', async () => {
|
||||
await form.value.submit()
|
||||
|
||||
expect(form.value.errors).toMatchObject([
|
||||
{ id: 'emailInput', name: 'email', message: 'Required' },
|
||||
{ id: 'passwordInput', name: 'password', message: 'Required' }
|
||||
])
|
||||
|
||||
expect(wrapper.setupState.onSubmit).not.toHaveBeenCalled()
|
||||
expect(wrapper.setupState.onError).toHaveBeenCalledTimes(1)
|
||||
expect(wrapper.setupState.onError).toHaveBeenCalledWith(expect.objectContaining({
|
||||
errors: [
|
||||
{ id: 'emailInput', name: 'email', message: 'Required' },
|
||||
{ id: 'passwordInput', name: 'password', message: 'Required' }
|
||||
]
|
||||
}))
|
||||
|
||||
const emailField = wrapper.find('#emailField')
|
||||
expect(emailField.text()).toBe('Required')
|
||||
|
||||
const passwordField = wrapper.find('#passwordField')
|
||||
expect(passwordField.text()).toBe('Required')
|
||||
})
|
||||
|
||||
test('valid submit works', async () => {
|
||||
state.email = 'bob@dylan.com'
|
||||
state.password = 'strongpassword'
|
||||
|
||||
await form.value.submit()
|
||||
|
||||
expect(wrapper.setupState.onSubmit).toHaveBeenCalledTimes(1)
|
||||
expect(wrapper.setupState.onSubmit).toHaveBeenCalledWith(expect.objectContaining({
|
||||
data: {
|
||||
email: 'bob@dylan.com',
|
||||
password: 'strongpassword'
|
||||
}
|
||||
}))
|
||||
|
||||
expect(wrapper.setupState.onError).toHaveBeenCalledTimes(0)
|
||||
})
|
||||
|
||||
test('validate works', async () => {
|
||||
await expect(form.value.validate).rejects.toThrow('Form validation exception')
|
||||
|
||||
state.email = 'bob@dylan.com'
|
||||
state.password = 'strongpassword'
|
||||
|
||||
expect(await form.value.validate()).toMatchObject({
|
||||
email: 'bob@dylan.com',
|
||||
password: 'strongpassword'
|
||||
})
|
||||
})
|
||||
|
||||
test('getErrors works', async () => {
|
||||
await form.value.submit()
|
||||
const errors = form.value.getErrors()
|
||||
|
||||
expect(errors).toMatchObject([
|
||||
{ id: 'emailInput', name: 'email', message: 'Required' },
|
||||
{ id: 'passwordInput', name: 'password', message: 'Required' }
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('nested', async () => {
|
||||
let wrapper: any
|
||||
let form: any
|
||||
let state: any
|
||||
|
||||
beforeEach(async () => {
|
||||
wrapper = await mountSuspended({
|
||||
components: {
|
||||
UFormField,
|
||||
UForm,
|
||||
UInput
|
||||
},
|
||||
setup () {
|
||||
const form = ref()
|
||||
const state = reactive({ nested: {} })
|
||||
const schema = z.object({
|
||||
email: z.string().email(),
|
||||
password: z.string().min(8)
|
||||
})
|
||||
|
||||
const showNested = ref(true)
|
||||
const nestedSchema = z.object({
|
||||
field: z.string().min(1)
|
||||
})
|
||||
|
||||
|
||||
const onError = vi.fn()
|
||||
const onSubmit = vi.fn()
|
||||
|
||||
return { state, schema, nestedSchema, form, onSubmit, onError, showNested }
|
||||
},
|
||||
template: `
|
||||
<UForm ref="form" :state="state" :schema="schema" @submit="onSubmit" @error="onError">
|
||||
<UFormField id="emailField" name="email">
|
||||
<UInput id="emailInput" v-model="state.email" />
|
||||
</UFormField>
|
||||
<UFormField id="passwordField" name="password">
|
||||
<UInput id="passwordInput" v-model="state.password" />
|
||||
</UFormField>
|
||||
|
||||
<UForm v-if="showNested" ref="nestedForm" :state="state.nested" :schema="nestedSchema">
|
||||
<UFormField id="nestedField" name="field">
|
||||
<UInput id="nestedInput" v-model="state.nested.field" />
|
||||
</UFormField>
|
||||
</UForm>
|
||||
</UForm>
|
||||
`
|
||||
})
|
||||
form = wrapper.setupState.form
|
||||
state = wrapper.setupState.state
|
||||
})
|
||||
|
||||
test('submit error works', async () => {
|
||||
await form.value.submit()
|
||||
|
||||
expect(wrapper.setupState.onSubmit).not.toHaveBeenCalled()
|
||||
expect(wrapper.setupState.onError).toHaveBeenCalledTimes(1)
|
||||
const onErrorCallArgs = wrapper.setupState.onError.mock.lastCall[0]
|
||||
expect(onErrorCallArgs.childrens[0].errors).toMatchObject([ { id: 'nestedInput', name: 'field', message: 'Required' } ])
|
||||
expect(onErrorCallArgs.errors).toMatchObject([
|
||||
{ id: 'emailInput', name: 'email', message: 'Required' },
|
||||
{ id: 'passwordInput', name: 'password', message: 'Required' }
|
||||
])
|
||||
|
||||
const nestedField = wrapper.find('#nestedField')
|
||||
expect(nestedField.text()).toBe('Required')
|
||||
})
|
||||
|
||||
test('submit works when child is disabled', async () => {
|
||||
await form.value.submit()
|
||||
expect(wrapper.setupState.onError).toHaveBeenCalledTimes(1)
|
||||
vi.resetAllMocks()
|
||||
|
||||
wrapper.setupState.showNested.value = false
|
||||
await nextTick()
|
||||
|
||||
state.email = 'bob@dylan.com'
|
||||
state.password = 'strongpassword'
|
||||
|
||||
await form.value.submit()
|
||||
expect(wrapper.setupState.onSubmit).toHaveBeenCalledTimes(1)
|
||||
expect(wrapper.setupState.onError).toHaveBeenCalledTimes(0)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`Form > custom validation works > with error 1`] = `
|
||||
"<form class="">
|
||||
"<form id="42" class="">
|
||||
<div data-v-0fd934a4="" class="text-sm">
|
||||
<div data-v-0fd934a4="" class="">
|
||||
<!--v-if-->
|
||||
@@ -36,7 +36,7 @@ exports[`Form > custom validation works > with error 1`] = `
|
||||
`;
|
||||
|
||||
exports[`Form > custom validation works > without error 1`] = `
|
||||
"<form class="">
|
||||
"<form id="42" class="">
|
||||
<div data-v-0fd934a4="" class="text-sm">
|
||||
<div data-v-0fd934a4="" class="">
|
||||
<!--v-if-->
|
||||
@@ -71,7 +71,7 @@ exports[`Form > custom validation works > without error 1`] = `
|
||||
`;
|
||||
|
||||
exports[`Form > joi validation works > with error 1`] = `
|
||||
"<form class="">
|
||||
"<form id="42" class="">
|
||||
<div data-v-0fd934a4="" class="text-sm">
|
||||
<div data-v-0fd934a4="" class="">
|
||||
<!--v-if-->
|
||||
@@ -106,7 +106,7 @@ exports[`Form > joi validation works > with error 1`] = `
|
||||
`;
|
||||
|
||||
exports[`Form > joi validation works > without error 1`] = `
|
||||
"<form class="">
|
||||
"<form id="42" class="">
|
||||
<div data-v-0fd934a4="" class="text-sm">
|
||||
<div data-v-0fd934a4="" class="">
|
||||
<!--v-if-->
|
||||
@@ -140,12 +140,12 @@ exports[`Form > joi validation works > without error 1`] = `
|
||||
</form>"
|
||||
`;
|
||||
|
||||
exports[`Form > renders basic case correctly 1`] = `"<form class=""></form>"`;
|
||||
exports[`Form > renders basic case correctly 1`] = `"<form id="0" class=""></form>"`;
|
||||
|
||||
exports[`Form > renders with default slot correctly 1`] = `"<form class="">Form slot</form>"`;
|
||||
exports[`Form > renders with default slot correctly 1`] = `"<form id="1" class="">Form slot</form>"`;
|
||||
|
||||
exports[`Form > valibot validation works > with error 1`] = `
|
||||
"<form class="">
|
||||
"<form id="42" class="">
|
||||
<div data-v-0fd934a4="" class="text-sm">
|
||||
<div data-v-0fd934a4="" class="">
|
||||
<!--v-if-->
|
||||
@@ -180,7 +180,7 @@ exports[`Form > valibot validation works > with error 1`] = `
|
||||
`;
|
||||
|
||||
exports[`Form > valibot validation works > without error 1`] = `
|
||||
"<form class="">
|
||||
"<form id="42" class="">
|
||||
<div data-v-0fd934a4="" class="text-sm">
|
||||
<div data-v-0fd934a4="" class="">
|
||||
<!--v-if-->
|
||||
@@ -215,7 +215,7 @@ exports[`Form > valibot validation works > without error 1`] = `
|
||||
`;
|
||||
|
||||
exports[`Form > yup validation works > with error 1`] = `
|
||||
"<form class="">
|
||||
"<form id="42" class="">
|
||||
<div data-v-0fd934a4="" class="text-sm">
|
||||
<div data-v-0fd934a4="" class="">
|
||||
<!--v-if-->
|
||||
@@ -250,7 +250,7 @@ exports[`Form > yup validation works > with error 1`] = `
|
||||
`;
|
||||
|
||||
exports[`Form > yup validation works > without error 1`] = `
|
||||
"<form class="">
|
||||
"<form id="42" class="">
|
||||
<div data-v-0fd934a4="" class="text-sm">
|
||||
<div data-v-0fd934a4="" class="">
|
||||
<!--v-if-->
|
||||
@@ -285,7 +285,7 @@ exports[`Form > yup validation works > without error 1`] = `
|
||||
`;
|
||||
|
||||
exports[`Form > zod validation works > with error 1`] = `
|
||||
"<form class="">
|
||||
"<form id="42" class="">
|
||||
<div data-v-0fd934a4="" class="text-sm">
|
||||
<div data-v-0fd934a4="" class="">
|
||||
<!--v-if-->
|
||||
@@ -320,7 +320,7 @@ exports[`Form > zod validation works > with error 1`] = `
|
||||
`;
|
||||
|
||||
exports[`Form > zod validation works > without error 1`] = `
|
||||
"<form class="">
|
||||
"<form id="42" class="">
|
||||
<div data-v-0fd934a4="" class="text-sm">
|
||||
<div data-v-0fd934a4="" class="">
|
||||
<!--v-if-->
|
||||
|
||||
Reference in New Issue
Block a user