Back
VueMediumNew
How do you handle forms and validate user input in Vue?
v-model plus validation logic or a library like VeeValidate
Ideal Answer
Basic form handling uses v-model for two-way binding on inputs, with reactive state for validation errors:
JavaScript
<script setup>
import { ref, computed } from 'vue'
const email = ref('')
const error = computed(() =>
email.value.includes('@') ? '' : 'Invalid email'
)
</script>
<template>
<input v-model="email" @blur="touched = true" />
<span v-if="touched && error">{{ error }}</span>
</template>
For complex forms (nested fields, async validation, schema-based rules), libraries like VeeValidate or @vueuse/core's form utilities, often paired with schema validators like Zod or Yup, are commonly used instead of hand-rolled logic.