Validation and Error Handling

Introduction And Lesson Overview

Welcome back! In the previous lesson, you learned how to build a Todo Application using Vue’s Composition API, focusing on advanced form handling and clean code structure. Now, we are going to take your skills a step further by exploring validation and error handling in forms. These are essential features in any real-world application. Without proper validation, users might submit incomplete or incorrect data, which can lead to confusion or even bugs in your app. Error handling, on the other hand, helps you provide clear feedback to users, making your application more user-friendly and professional.

In this lesson, you will learn how to add reactive validation to your Todo form, display helpful error messages, and manage the form’s state after submission. By the end, you will be able to create forms that not only collect data but also guide users to enter valid information. This lesson builds directly on the concepts you practiced earlier, so you will see how everything fits together in a real Vue component.

Recap Of Advanced Form Handling

Let’s quickly review what you accomplished in the last lesson. You built a Todo Application where users could add new tasks using a form. You used Vue’s ref to create reactive variables and the script setup syntax to keep your code organized. The form used v-model for two-way binding, so the input field and your component’s state stayed in sync. When the form was submitted, you checked that the input was not empty, emitted a custom event to the parent component, and reset the input field.

Now, you are ready to make your form even smarter. While you already checked for empty input before adding a new task, you did not provide any feedback to the user if they tried to submit an empty task. This is where validation and error handling come in. By adding these features, you will help users understand what went wrong and how to fix it, making your application much more robust.

Implementing Reactive Validation

To add validation to your form, you will use Vue’s computed properties. Computed properties are perfect for validation because they automatically update whenever their dependencies change. In your TodoForm.vue component, you can create a computed property called isInvalid that checks if the input is empty or contains only spaces.

Here is how you can set this up:

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

const newTodoText = ref('');
const hasSubmitted = ref(false);
const emit = defineEmits(['add-todo']);

// Computed property for validation. It's true if the input is invalid.
const isInvalid = computed(() => newTodoText.value.trim() === '');
</script>

In this example, isInvalid will be true if the input is empty or just spaces, and false otherwise. This property will update automatically as the user types. You also have a hasSubmitted variable to track if the user has tried to submit the form. This helps you decide when to show error messages.

Understanding Vue Directives for Conditional UI

Before we start showing validation messages in the UI, it’s important to understand a few Vue directives that make conditional behavior easy to implement. These directives let you show or hide elements, disable buttons, and style inputs dynamically based on your component’s state.

Conditional Rendering with `v-if`

The v-if directive allows you to display an element only when a certain condition is true. Vue simply removes the element from the DOM when the condition is false:

<p v-if="showError">This message appears only when showError is true.</p>

This is perfect for showing error messages only when the user needs to see them.

Disabling Elements with `:disabled`

You can disable form controls by binding a boolean expression to the disabled attribute:

<button :disabled="isInvalid">
  Add Task
</button>

When isInvalid is true, the button becomes unclickable. This is a helpful way to prevent users from submitting invalid data.

Dynamic CSS Classes with `:class`

Vue also makes it easy to apply CSS classes based on state. Using object syntax, you can toggle classes on and off:

<input :class="{ 'error-input': hasError }" />

This is useful for highlighting form fields when something is wrong, giving users clear visual feedback.

Displaying Error Feedback In The UI

Now that you have a way to check if the input is valid, you need to show feedback to the user. You can use Vue’s conditional rendering to display an error message only when the user tries to submit an invalid task. You can also add a CSS class to the input field to highlight the error visually.

Here is how you can do this in your template:

<template>
  <form @submit.prevent="handleSubmit" class="todo-form">
    <div class="input-wrapper">
      <input
        v-model="newTodoText"
        type="text"
        placeholder="Add a new task..."
        :class="{ 'invalid-input': showError }"
      />
      <p v-if="showError" class="error-message">Task cannot be empty.</p>
    </div>
    <button type="submit" :disabled="isInvalid && hasSubmitted">Add Task</button>
  </form>
</template>

The showError computed property is used to decide when to show the error message and apply the invalid-input class. It is defined like this:

const showError = computed(() => hasSubmitted.value && isInvalid.value);

This means the error message and red border will only appear after the user tries to submit the form with invalid input. Before that, the form looks normal. This approach avoids distracting the user with errors before they have even interacted with the form.

When the user tries to submit an empty task, the UI will look like this:

[ Add a new task... ]  (input field with red border)
Task cannot be empty.  (error message in red)
[Add Task]  (button, possibly disabled)

Managing Form Submission And Resetting State

Handling form submission with validation is a key part of a good user experience. In your handleSubmit function, you first set hasSubmitted to true to indicate that the user has tried to submit the form. If the input is valid, you emit the add-todo event, clear the input, and reset hasSubmitted to false so the form is ready for the next entry. If the input is invalid, the error message appears and the form stays in place, allowing the user to correct their input.

Here is the relevant part of the script:

function handleSubmit() {
  hasSubmitted.value = true;
  if (!isInvalid.value) {
    emit('add-todo', newTodoText.value.trim());
    newTodoText.value = '';
    hasSubmitted.value = false; // Reset for the next entry
  }
}

This logic ensures that users cannot submit empty tasks and that the form resets properly after a successful submission. If a user enters a valid task, the form clears and is ready for another entry. If they try to submit an empty task, the error message appears and the input stays highlighted until they fix it.

Summary And Next Steps

In this lesson, you learned how to add reactive validation and error handling to your Todo form using Vue’s Composition API. You saw how computed properties like isInvalid and showError help you check user input and control when to display error messages. You also learned how to use conditional rendering and dynamic CSS classes to give clear feedback to users, and how to manage the form’s state after submission.

These techniques are essential for building forms that are both user-friendly and reliable. By guiding users to enter valid data and providing helpful feedback, you make your application more professional and enjoyable to use.

You are now ready to practice these skills with hands-on exercises. Keep up the great work! Each step you take brings you closer to mastering advanced forms and reactivity in Vue.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal