Skip to content

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.

js
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

html
js
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.

html
js
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.

html
js
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.

html
js
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.

html
js
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.

html
js
import { ref } from'vue'; exportdefault { setup() { const value = ref(1); return { value }; }, };

⭐ Field Type - Rate

html
js
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.

html
js
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.

html
js
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.

html
js
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.

html
js
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.

html
js
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

html
js
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

AttributeDescriptionTypeDefault
label-widthField label width*numberstring*
label-alignField label align, can be set to center``right``topstringleft
input-alignField input align, can be set to center``rightstringleft
error-message-alignError message align, can be set to center``rightstringleft
validate-triggerWhen to validate the form, can be set to onChange��onSubmit, supports using array to set multiple values*stringstring[]*
colonWhether to display colon after labelbooleanfalse
disabledWhether to disable formbooleanfalse
readonlyWhether to be readonlybooleanfalse
required v4.7.3Whether to show required mark*boolean'auto'*
validate-firstWhether to stop the validation when a rule failsbooleanfalse
scroll-to-errorWhether to scroll to the error field when validation failedbooleanfalse
scroll-to-error-position v4.9.2The position when scrolling to the wrong form item, can be set to centerendnearest
show-errorWhether to highlight input when validation failedbooleanfalse
show-error-messageWhether to show error message when validation failedbooleantrue
submit-on-enterWhether to submit form on enterbooleantrue

📏 Data Structure of Rule

Build robust validation with flexible rule configurations! 🛡️ Create custom validation logic that ensures data quality and user experience.

KeyDescriptionType
requiredWhether to be a required field, the value is not allowed to be empty (empty string, empty array, false, undefined, null)boolean
messageError message, can be a function to dynamically return message content*string
validatorCustom validator, can return a Promise to validate dynamically*(value, rule) => boolean
patternRegexp pattern, if the regexp cannot match, means that the validation failsRegExp
triggerWhen to validate the form, priority is higher than the validate-trigger of the Form component, can be set to onChange, onBlur, onSubmit*string
formatterFormat value before validate(value, rule) => any
validateEmptyControls whether the validator and pattern options to verify empty values, the default value is true, you can set to false to disable this behaviorboolean

⚡ validate-trigger

Control when validation happens! 🎯 Choose the perfect timing for user feedback and form validation.

ValueDescription
onSubmitTrigger validation after submitting form
onBlurTrigger validation after submitting form or blurring input
onChangeTrigger validation after submitting form or changing input value

🎯 Events

Stay connected with form interactions! 📡 Handle submissions and validation feedback with these essential events.

EventDescriptionArguments
submitEmitted after submitting the form and validation passedvalues: object
failedEmitted after submitting the form and validation failederrorInfo: { 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.

NameDescriptionAttributeReturn value
submitSubmit form--
getValuesGet current form values-Record<string, unknown>
validateValidate form*name?: stringstring[]*
resetValidationReset validation*name?: stringstring[]*
getValidationStatusGet validation status of all fields��status can be passed��failed��unvalidated-Record<string, FieldValidationStatus>
scrollToFieldScroll to fieldname: 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:

ts
importtype { FormProps, FormInstance } from'vant';

FormInstance is the type of component instance:

ts
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.

NameDescription
defaultForm content

Explore related components and features! 🔗 Build comprehensive form experiences with these complementary tools.

Enterprise-level mobile solution based on Vant