Form - Vant 4
Form
Build powerful, validated forms with ease! 🚀 Create seamless data collection experiences for your users.
📝 Intro
Your complete solution for data entry and validation! 🎯 Supports a comprehensive range of input types including text fields, radio buttons, checkboxes, file uploads, and much more. Designed to work seamlessly with the Field component for maximum flexibility and control. ✨
📦 Install
Get started with Form components in seconds! 🚀 Register the components globally via app.use, or refer to Component Registration for more registration options.
import { createApp } from'vue'; import { Form, Field, CellGroup } from'vant'; const app = createApp(); app.use(Form); app.use(Field); app.use(CellGroup);🎯 Usage
Transform your data collection with these powerful form patterns! ✨
🌟 Basic Usage
import { ref } from'vue'; exportdefault { setup() { const username = ref(''); const password = ref(''); constonSubmit = (values) => { console.log('submit', values); }; return { username, password, onSubmit, }; }, };✅ Validate Rules
Ensure data quality with powerful validation! 🛡️ Set up comprehensive rules including patterns, custom validators, and async validation for bulletproof forms.
import { ref } from'vue'; import { closeToast, showLoadingToast } from'vant'; exportdefault { setup() { const value1 = ref(''); const value2 = ref(''); const value3 = ref('abc'); const value4 = ref(''); const pattern = /\d{6}/; constvalidator = (val) => /1\d{10}/.test(val); constvalidatorMessage = (val) => `${val} is invalid`; constasyncValidator = (val) => newPromise((resolve) => { showLoadingToast('Validating...'); setTimeout(() => { closeToast(); resolve(val === '1234'); }, 1000); }); constonFailed = (errorInfo) => { console.log('failed', errorInfo); }; return { value1, value2, value3, value4, pattern, onFailed, validator, asyncValidator, validatorMessage, }; }, };🔄 Field Type - Switch
Toggle options with style! 🎛️ Perfect for boolean settings and on/off controls.
import { ref } from'vue'; exportdefault { setup() { const checked = ref(false); return { checked }; }, };☑️ Field Type - Checkbox
Multiple selections made easy! ✨ Great for feature preferences and multi-option forms.
import { ref } from'vue'; exportdefault { setup() { const checked = ref(false); const groupChecked = ref([]); return { checked, groupChecked, }; }, };📻 Field Type - Radio
Single choice selection! 🎯 Perfect for exclusive options and preference settings.
import { ref } from'vue'; exportdefault { setup() { const checked = ref('1'); return { checked }; }, };🔢 Field Type - Stepper
Precise number input! ⚡ Ideal for quantities, counts, and numeric adjustments.
import { ref } from'vue'; exportdefault { setup() { const value = ref(1); return { value }; }, };⭐ Field Type - Rate
import { ref } from'vue'; exportdefault { setup() { const value = ref(3); return { value }; }, };🎚️ Field Type - Slider
Smooth value selection! 🎯 Perfect for ranges, volumes, and adjustable parameters.
import { ref } from'vue'; exportdefault { setup() { const value = ref(50); return { value }; }, };📤 Field Type - Uploader
File uploads made simple! 🚀 Handle images, documents, and media with elegant preview and progress tracking.
import { ref } from'vue'; exportdefault { setup() { const value = ref([ { url: 'https://fastly.jsdelivr.net/npm/@vant/assets/leaf.jpeg' }, ]); return { value }; }, };🎯 Field Type - Picker
Smart selection from lists! ✨ Perfect for categories, options, and structured choices.
import { ref } from'vue'; exportdefault { setup() { const result = ref(''); const pickerValue = ref([]); const showPicker = ref(false); const columns = [ { text: 'Delaware', value: 'Delaware' }, { text: 'Florida', value: 'Florida' }, { text: 'Georgia', value: 'Georgia' }, { text: 'Indiana', value: 'Indiana' }, { text: 'Maine', value: 'Maine' }, ]; constonConfirm = ({ selectedValues, selectedOptions }) => { result.value = selectedOptions[0]?.text; pickerValue.value = selectedValues; showPicker.value = false; }; return { result, pickerValue, columns, onConfirm, showPicker, }; }, };📅 Field Type - DatePicker
Intuitive date selection! 🗓️ Beautiful calendar interface for appointments, deadlines, and scheduling.
import { ref } from'vue'; exportdefault { setup() { const result = ref(''); const showPicker = ref(false); const pickerValue = ref<string[]>([]); constonConfirm = ({ selectedValues }) => { result.value = selectedValues.join('/'); pickerValue.value = selectedValues; showPicker.value = false; }; return { result, pickerValue, onConfirm, showPicker, }; }, };🌍 Field Type - Area
Geographic location selection! 📍 Choose countries, states, and cities with hierarchical navigation.
import { ref } from'vue'; import { areaList } from'@vant/area-data'; exportdefault { setup() { const result = ref(''); const showArea = ref(false); const pickerValue = ref(''); constonConfirm = ({ selectedValues, selectedOptions }) => { pickerValue.value = selectedValues.length ? selectedValues[selectedValues.length - 1] : ''; showArea.value = false; result.value = selectedOptions.map((item) => item.text).join('/'); }; return { result, areaList, pickerValue, showArea, onConfirm, }; }, };📆 Field Type - Calendar
import { ref } from'vue'; exportdefault { setup() { const result = ref(''); const showCalendar = ref(false); constonConfirm = (date) => { result.value = `${date.getMonth() + 1}/${date.getDate()}`; showCalendar.value = false; }; return { result, onConfirm, showCalendar, }; }, };🔧 API
Complete control over your form's behavior and appearance! 🎛️ Configure every aspect from layout to validation with these comprehensive options.
📋 Props
| Attribute | Description | Type | Default |
|---|---|---|---|
| label-width | Field label width | *number | string* |
| label-align | Field label align, can be set to center``right``top | string | left |
| input-align | Field input align, can be set to center``right | string | left |
| error-message-align | Error message align, can be set to center``right | string | left |
| validate-trigger | When to validate the form, can be set to onChange��onSubmit, supports using array to set multiple values | *string | string[]* |
| colon | Whether to display colon after label | boolean | false |
| disabled | Whether to disable form | boolean | false |
| readonly | Whether to be readonly | boolean | false |
required v4.7.3 | Whether to show required mark | *boolean | 'auto'* |
| validate-first | Whether to stop the validation when a rule fails | boolean | false |
| scroll-to-error | Whether to scroll to the error field when validation failed | boolean | false |
scroll-to-error-position v4.9.2 | The position when scrolling to the wrong form item, can be set to center | end | nearest |
| show-error | Whether to highlight input when validation failed | boolean | false |
| show-error-message | Whether to show error message when validation failed | boolean | true |
| submit-on-enter | Whether to submit form on enter | boolean | true |
📏 Data Structure of Rule
Build robust validation with flexible rule configurations! 🛡️ Create custom validation logic that ensures data quality and user experience.
| Key | Description | Type |
|---|---|---|
| required | Whether to be a required field, the value is not allowed to be empty (empty string, empty array, false, undefined, null) | boolean |
| message | Error message, can be a function to dynamically return message content | *string |
| validator | Custom validator, can return a Promise to validate dynamically | *(value, rule) => boolean |
| pattern | Regexp pattern, if the regexp cannot match, means that the validation fails | RegExp |
| trigger | When to validate the form, priority is higher than the validate-trigger of the Form component, can be set to onChange, onBlur, onSubmit | *string |
| formatter | Format value before validate | (value, rule) => any |
| validateEmpty | Controls whether the validator and pattern options to verify empty values, the default value is true, you can set to false to disable this behavior | boolean |
⚡ validate-trigger
Control when validation happens! 🎯 Choose the perfect timing for user feedback and form validation.
| Value | Description |
|---|---|
| onSubmit | Trigger validation after submitting form |
| onBlur | Trigger validation after submitting form or blurring input |
| onChange | Trigger validation after submitting form or changing input value |
🎯 Events
Stay connected with form interactions! 📡 Handle submissions and validation feedback with these essential events.
| Event | Description | Arguments |
|---|---|---|
| submit | Emitted after submitting the form and validation passed | values: object |
| failed | Emitted after submitting the form and validation failed | errorInfo: { values: object, errors: object[] } |
🛠️ Methods
Programmatic control at your fingertips! 🎮 Access powerful methods to manage form state and behavior dynamically.
Use ref to get Form instance and call instance methods.
| Name | Description | Attribute | Return value |
|---|---|---|---|
| submit | Submit form | - | - |
| getValues | Get current form values | - | Record<string, unknown> |
| validate | Validate form | *name?: string | string[]* |
| resetValidation | Reset validation | *name?: string | string[]* |
| getValidationStatus | Get validation status of all fields��status can be passed��failed��unvalidated | - | Record<string, FieldValidationStatus> |
| scrollToField | Scroll to field | name: string, alignToTop: boolean | - |
📝 Types
Full TypeScript support for enhanced development! 🚀 Import these types for better code completion and type safety.
The component exports the following type definitions:
importtype { FormProps, FormInstance } from'vant';FormInstance is the type of component instance:
import { ref } from'vue'; importtype { FormInstance } from'vant'; const formRef = ref<FormInstance>(); formRef.value?.submit();🎨 Slots
Flexible content customization! ✨ Extend your form with custom layouts and components through slots.
| Name | Description |
|---|---|
| default | Form content |
📚 Related Docs
Explore related components and features! 🔗 Build comprehensive form experiences with these complementary tools.
- Field - Individual form fields with validation
- Button - Submit and action buttons
- Checkbox - Multiple choice selections
- Radio - Single choice selections
- Switch - Toggle controls
- Stepper - Numeric input controls
- Rate - Rating and scoring inputs
- Slider - Range value selection
- Uploader - File upload functionality
- Picker - Option selection from lists
- DatePicker - Date and time selection
- Area - Geographic location picker
- Calendar - Calendar date selection
- Search - Search input fields
- PasswordInput - Secure password entry
- NumberKeyboard - Numeric input keyboard
- ConfigProvider - Global configuration
- Advanced Usage - Advanced implementation patterns