Skip to content

Commit

Permalink
feat(Form): add valibot supprt (#615)
Browse files Browse the repository at this point in the history
Co-authored-by: Benjamin Canac <canacb1@gmail.com>
  • Loading branch information
Sevichecc and benjamincanac committed Sep 7, 2023
1 parent eebff72 commit ab5153a
Show file tree
Hide file tree
Showing 5 changed files with 130 additions and 4 deletions.
42 changes: 42 additions & 0 deletions docs/components/content/examples/FormExampleValibot.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<script setup lang="ts">
import { ref } from 'vue'
import { string, object, email, minLength, Input } from 'valibot'
import type { FormSubmitEvent } from '@nuxt/ui/dist/runtime/types'
const schema = object({
email: string([email('Invalid email')]),
password: string([minLength(8, 'Must be at least 8 characters')])
})
type Schema = Input<typeof schema>
const state = ref({
email: undefined,
password: undefined
})
async function submit (event: FormSubmitEvent<Schema>) {
// Do something with event.data
console.log(event.data)
}
</script>

<template>
<UForm
:schema="schema"
:state="state"
@submit="submit"
>
<UFormGroup label="Email" name="email">
<UInput v-model="state.email" />
</UFormGroup>

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

<UButton type="submit">
Submit
</UButton>
</UForm>
</template>
57 changes: 55 additions & 2 deletions docs/content/3.forms/10.form.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ links:

## Usage

Use the Form component to validate form data using schema libraries such as [Yup](https://github.com/jquense/yup), [Zod](https://github.com/colinhacks/zod), [Joi](https://github.com/hapijs/joi) or your own validation logic. It works seamlessly with the FormGroup component to automatically display error messages around form elements.
Use the Form component to validate form data using schema libraries such as [Yup](https://github.com/jquense/yup), [Zod](https://github.com/colinhacks/zod), [Joi](https://github.com/hapijs/joi), [Valibot](https://valibot.dev/) or your own validation logic. It works seamlessly with the FormGroup component to automatically display error messages around form elements.

The Form component requires the `validate` and `state` props for form validation.

Expand Down Expand Up @@ -69,7 +69,7 @@ async function submit (event: FormSubmitEvent<any>) {

## Schema

You can provide a schema from [Yup](#yup), [Zod](#zod) or [Joi](#joi) through the `schema` prop to validate the state. It's important to note that **none of these libraries are included** by default, so make sure to **install the one you need**.
You can provide a schema from [Yup](#yup), [Zod](#zod) or [Joi](#joi), [Valibot](#valibot) through the `schema` prop to validate the state. It's important to note that **none of these libraries are included** by default, so make sure to **install the one you need**.

### Yup

Expand Down Expand Up @@ -232,6 +232,59 @@ async function submit (event: FormSubmitEvent<any>) {
```
::

### Valibot

::component-example
#default
:form-example-valibot{class="space-y-4 w-60"}

#code
```vue
<script setup lang="ts">
import { ref } from 'vue'
import { string, object, email, minLength, Input } from 'valibot'
import type { FormSubmitEvent } from '@nuxt/ui/dist/runtime/types'
const schema = object({
email: string([email('Invalid email')]),
password: string([minLength(8, 'Must be at least 8 characters')])
})
type Schema = Input<typeof schema>
const state = ref({
email: undefined,
password: undefined
})
async function submit (event: FormSubmitEvent<Schema>) {
// Do something with event.data
console.log(event.data)
}
</script>
<template>
<UForm
:schema="schema"
:state="state"
@submit="submit"
>
<UFormGroup label="Email" name="email">
<UInput v-model="state.email" />
</UFormGroup>
<UFormGroup label="Password" name="password">
<UInput v-model="state.password" type="password" />
</UFormGroup>
<UButton type="submit">
Submit
</UButton>
</UForm>
</template>
```
::

## Other libraries

For other validation libraries, you can define your own component with custom validation logic.
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@
"unbuild": "^2.0.0",
"vue-tsc": "^1.8.10",
"yup": "^1.2.0",
"zod": "^3.22.2"
"zod": "^3.22.2",
"valibot": "^0.13.1"
},
"pnpm": {
"patchedDependencies": {
Expand Down
7 changes: 7 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 24 additions & 1 deletion src/runtime/components/forms/Form.vue
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import { useEventBus } from '@vueuse/core'
import type { ZodSchema } from 'zod'
import type { ValidationError as JoiError, Schema as JoiSchema } from 'joi'
import type { ObjectSchema as YupObjectSchema, ValidationError as YupError } from 'yup'
import type { ObjectSchema as ValibotObjectSchema } from 'valibot'
import { safeParseAsync } from 'valibot'
import type { FormError, FormEvent, FormEventType, FormSubmitEvent, Form } from '../../types/form'
export default defineComponent({
Expand All @@ -18,7 +20,8 @@ export default defineComponent({
type: Object as
| PropType<ZodSchema>
| PropType<YupObjectSchema<any>>
| PropType<JoiSchema>,
| PropType<JoiSchema>
| PropType<ValibotObjectSchema<any>>,
default: undefined
},
state: {
Expand Down Expand Up @@ -61,6 +64,8 @@ export default defineComponent({
errs = errs.concat(await getYupErrors(props.state, props.schema))
} else if (isJoiSchema(props.schema)) {
errs = errs.concat(await getJoiErrors(props.state, props.schema))
} else if (isValibotSchema(props.schema)) {
errs = errs.concat(await getValibotError(props.state, props.schema))
} else {
throw new Error('Form validation failed: Unsupported form schema')
}
Expand Down Expand Up @@ -204,4 +209,22 @@ async function getJoiErrors (
}
}
}
function isValibotSchema (schema: any): schema is ValibotObjectSchema<any> {
return schema._parse !== undefined
}
async function getValibotError (
state: any,
schema: ValibotObjectSchema<any>
): Promise<FormError[]> {
const result = await safeParseAsync(schema, state)
if (result.success === false) {
return result.issues.map((issue) => ({
path: issue.path.map(p => p.key).join('.'),
message: issue.message
}))
}
return []
}
</script>

0 comments on commit ab5153a

Please sign in to comment.