Usage
Use the Form component to validate form data using any validation library supporting Standard Schema such as Valibot, Zod, Regle, Yup, Joi or Superstruct or your own validation logic.
It works with the FormField component to display error messages around form elements automatically.
Schema validation
It requires two props:
state- a reactive object holding the form's state.schema- any Standard Schema or Superstruct.
Errors are reported directly to the FormField component based on the name or error-pattern prop. This means the validation rules defined for the email attribute in your schema will be applied to <FormField name="email">.
Nested validation rules are handled using dot notation. For example, a rule like { user: z.object({ email: z.string() }) } will be applied to <FormField name="user.email">.
Custom validation
Use the validate prop to apply your own validation logic.
The validation function must return a list of errors with the following attributes:
message- the error message to display.name- thenameof theFormFieldto send the error to.
schema prop to handle complex use cases.Input events
The Form component automatically triggers validation when an input emits an input, change, or blur event.
- Validation on
inputoccurs as you type. - Validation on
changeoccurs when you commit to a value. - Validation on
blurhappens when an input loses focus.
You can control when validation happens this using the validate-on prop.
useFormField composable to implement this inside your own components.Error event
You can listen to the @error event to handle errors. This event is triggered when the form is submitted and contains an array of FormError objects with the following fields:
id- the input'sid.name- thenameof theFormFieldmessage- the error message to display.
Here's an example that focuses the first input element with an error after the form is submitted:
Nesting forms
Use the nested prop to nest multiple Form components and link their validation functions. In this case, validating the parent form will automatically validate all the other forms inside it.
Nested forms directly inherit their parent's state, so you don't need to define a separate state for them. You can use the name prop to target a nested attribute within the parent's state.
It can be used to dynamically add fields based on user's input:
Or to validate list inputs:
API
Props
Slots
Emits
Expose
You can access the typed component instance using useTemplateRef.
<script setup lang="ts">
const form = useTemplateRef('form')
</script>
<template>
<B24Form ref="form" />
</template>
This will give you access to the following:
Theme
export default defineAppConfig({
b24ui: {
form: {
base: ''
}
}
})
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import bitrix24UIPluginVite from '@bitrix24/b24ui-nuxt/vite'
export default defineConfig({
plugins: [
vue(),
bitrix24UIPluginVite({
b24ui: {
form: {
base: ''
}
}
})
]
})