← Back to Vue.js Course | Chapter 5: Forms | Lesson 4 of 6

Form validation basics

Validating means checking values as the user types and showing helpful messages before submitting.

In this page:

  1. Form validation basics
Syntax
markup
export default {
  computed: {
    error() {
      return this.field ? '' : 'error message';
    }
  }
}

<p v-if="error">{{ error }}</p>

Form validation basics

A simple approach uses computed properties that return error messages based on the current data, and disables the submit button while there are errors.

For complex forms consider libraries like VeeValidate or Vuelidate. Always validate again on the server.

Note: Client-side validation is for user experience; the server must still validate.

Example: Form validation basics

markup
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
  <input v-model="email" placeholder="email">
  <span style="color:red">{{ error }}</span>
  <button :disabled="!!error">Sign up</button>
</div>
<script>
  Vue.createApp({
    data() { return { email: "" }; },
    computed: {
      error() {
        if (!this.email) return "Email is required";
        return /^\S+@\S+\.\S+$/.test(this.email) ? "" : "Enter a valid email";
      },
    },
  }).mount("#app");
  const i = document.querySelector("input");
  i.value = "[email protected]"; i.dispatchEvent(new window.Event("input"));
  Vue.nextTick(() => console.log("valid email -> button disabled:", document.querySelector("button").disabled));
</script>
</body>
</html>

<!-- Output:
Rendered: Sign up
console: valid email -> button disabled: false
-->
Live Example
Related Topics
Common Mistakes
  1. Trusting client-side validation only
  2. Showing errors before the user typed
  3. Not disabling submit while invalid
Chapter Summary
  • Computed properties can produce errors
  • Disable submit while invalid
  • Libraries help with large forms
  • Always validate on the server too
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.