0
0
VueHow-ToBeginner · 3 min read

How to Validate Form in Vue: Simple Guide with Examples

To validate a form in Vue, use reactive data properties to track input values and computed properties or methods to check validation rules. Bind input fields with v-model and show error messages conditionally based on validation results.
📐

Syntax

Use v-model to bind form inputs to data properties. Create computed properties or methods to validate these inputs. Use conditional rendering with v-if to show error messages.

Example parts:

  • v-model: binds input to data
  • Data properties: store input values
  • Computed properties or methods: return validation status
  • v-if: display errors when validation fails
vue
<template>
  <form @submit.prevent="submitForm">
    <input v-model="email" type="email" placeholder="Enter email" />
    <p v-if="emailError">{{ emailError }}</p>
    <button type="submit" :disabled="!isFormValid">Submit</button>
  </form>
</template>

<script setup>
import { ref, computed } from 'vue'

const email = ref('')

const emailError = computed(() => {
  if (!email.value) return 'Email is required.'
  const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailPattern.test(email.value)) return 'Email is invalid.'
  return ''
})

const isFormValid = computed(() => !emailError.value)

function submitForm() {
  alert('Form submitted with email: ' + email.value)
}
</script>
Output
A form with an email input. If empty or invalid, an error message appears below the input. The submit button is disabled until the email is valid.
💻

Example

This example shows a simple form with name and email fields. It validates that both fields are filled and email is in correct format. Errors appear below inputs, and the submit button is disabled until all validations pass.

vue
<template>
  <form @submit.prevent="submitForm" novalidate>
    <div>
      <label for="name">Name:</label>
      <input id="name" v-model="name" type="text" placeholder="Your name" />
      <p v-if="nameError" style="color: red">{{ nameError }}</p>
    </div>
    <div>
      <label for="email">Email:</label>
      <input id="email" v-model="email" type="email" placeholder="Your email" />
      <p v-if="emailError" style="color: red">{{ emailError }}</p>
    </div>
    <button type="submit" :disabled="!isFormValid">Submit</button>
  </form>
</template>

<script setup>
import { ref, computed } from 'vue'

const name = ref('')
const email = ref('')

const nameError = computed(() => {
  if (!name.value.trim()) return 'Name is required.'
  return ''
})

const emailError = computed(() => {
  if (!email.value) return 'Email is required.'
  const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailPattern.test(email.value)) return 'Email is invalid.'
  return ''
})

const isFormValid = computed(() => !nameError.value && !emailError.value)

function submitForm() {
  alert(`Submitted: Name=${name.value}, Email=${email.value}`)
}
</script>
Output
A form with name and email inputs. Error messages appear if fields are empty or email is invalid. Submit button is disabled until all inputs are valid. On submit, an alert shows the entered values.
⚠️

Common Pitfalls

Common mistakes when validating forms in Vue include:

  • Not using v-model for two-way binding, so input changes don't update data.
  • Not preventing default form submission with @submit.prevent, causing page reload.
  • Not trimming input values before validation, leading to false errors.
  • Disabling submit button without clear feedback, confusing users.
  • Using synchronous validation only, ignoring async needs (like server checks).
vue
<template>
  <form @submit="submitForm">
    <input v-model="email" type="email" />
    <button type="submit">Submit</button>
  </form>
</template>

<script setup>
import { ref } from 'vue'
const email = ref('')
function submitForm() {
  // This will reload page because no prevent
  alert('Submitted: ' + email.value)
}
</script>

<!-- Correct way -->
<template>
  <form @submit.prevent="submitForm">
    <input v-model.trim="email" type="email" />
    <button type="submit">Submit</button>
  </form>
</template>

<script setup>
import { ref } from 'vue'
const email = ref('')
function submitForm() {
  alert('Submitted: ' + email.value)
}
</script>
Output
First form reloads page on submit, losing data. Correct form prevents reload and trims input spaces.
📊

Quick Reference

  • v-model: Bind input to data.
  • Computed properties: Check validation rules reactively.
  • v-if: Show error messages conditionally.
  • @submit.prevent: Prevent page reload on form submit.
  • Trim inputs: Use v-model.trim to avoid whitespace errors.
  • Disable submit: Use :disabled to block invalid submissions.

Key Takeaways

Use v-model to bind form inputs to reactive data properties.
Validate inputs with computed properties or methods for reactive error checking.
Prevent default form submission with @submit.prevent to avoid page reload.
Show error messages conditionally using v-if for better user feedback.
Disable submit button until all validations pass to prevent invalid submissions.