Vue.js course ยท Module 5: Events & Forms

Advanced Forms

6 min read ยท
In this lesson3

NOVA LAB engineers are registering a new station module, and the form from the previous lessons is no longer enough for them. They want to select several systems to monitor at once, pick a module from a catalog that changes every week, and keep a two-letter name or a deployment year of 1999 out of the database. Each of these needs is one new form element.

Multi-select

The multiple attribute turns a drop-down list into a multiple-choice list. v-model then writes an array of the selected option values into the variable, so the variable must start as an empty array. The join(', ') method glues the array into a readable string.

<template>
  <div>
    <label>Select systems to monitor (Ctrl+Click):</label>
    <select v-model="selectedSystems" multiple>
      <option value="oxygen">Oxygen generator</option>
      <option value="water">Water recycler</option>
      <option value="power">Solar power</option>
      <option value="comms">Communications</option>
    </select>
    <p>Selected: {{ selectedSystems.join(', ') }}</p>
  </div>
</template>

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

const selectedSystems = ref([])
</script>

You select additional options while holding Ctrl, or Cmd on macOS. In the array the values appear in the order of the options in the list, not in the order of clicking, unlike with a checkbox group. The v-model syntax did not change, only the data type did. With three or four options, however, I recommend a checkbox group: it needs no hidden keyboard shortcut and shows all the choices at once.

Dynamic Options

The module catalog arrives as an array of objects with an id, a name and a sector. The options are generated by v-for, and :value="mod.id" writes the numeric id into the variable. The name of the selected module is looked up by a function using the find method, which returns the first element meeting a condition, or undefined. The ?. operator (optional chaining) reaches for name only when a module was found, and || '' turns a missing result into an empty string.

<template>
  <div>
    <select v-model="selectedModule">
      <option disabled value="">Select station module</option>
      <option
        v-for="mod in modules"
        :key="mod.id"
        :value="mod.id"
      >
        {{ mod.name }} ({{ mod.sector }})
      </option>
    </select>

    <p v-if="selectedModule">
      Selected: {{ getModuleName(selectedModule) }}
    </p>
  </div>
</template>

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

const modules = ref([
  { id: 1, name: 'Oxygen Alpha', sector: 'Sector A' },
  { id: 2, name: 'Plasma Beta', sector: 'Sector B' },
  { id: 3, name: 'Water Gamma', sector: 'Sector C' }
])

const selectedModule = ref('')

function getModuleName(id) {
  return modules.value.find(m => m.id === id)?.name || ''
}
</script>

Because :value preserves the type, selectedModule holds a number, and the strict comparison m.id === id works. The paragraph with v-if stays hidden as long as the variable holds an empty string. Adding a module to the modules array adds an option immediately, and the template does not need to be touched.

Form Validation

Validation answers three questions: what to check, when to check it and what to do with the result. Let us start with the template of the first two fields. Each has v-model, a @blur listener that runs validation after the field is left, and an error message that is visible only when it exists.

<template>
  <form @submit.prevent="submitForm">
    <div :class="{ error: errors.name }">
      <label>Module name:</label>
      <input v-model="form.name" @blur="validateName" />
      <span v-if="errors.name" class="error-message">
        {{ errors.name }}
      </span>
    </div>

    <div :class="{ error: errors.year }">
      <label>Deployment year:</label>
      <input v-model.number="form.year" type="number" @blur="validateYear" />
      <span v-if="errors.year" class="error-message">
        {{ errors.year }}
      </span>
    </div>

:class="{ error: errors.name }" adds the error CSS class when the message is not empty, so the field can light up in red. The year uses v-model.number, and the engineer field in the next part uses v-model.trim - you know both modifiers from the previous lesson. The second part of the template finishes the form with a button.

    <div :class="{ error: errors.engineer }">
      <label>Responsible engineer:</label>
      <input v-model.trim="form.engineer" @blur="validateEngineer" />
      <span v-if="errors.engineer" class="error-message">
        {{ errors.engineer }}
      </span>
    </div>

    <button type="submit" :disabled="!isFormValid">
      Register module
    </button>
  </form>
</template>

:disabled="!isFormValid" binds the attribute to a computed, so the button unlocks by itself once the form becomes valid. Without the colon, disabled="!isFormValid" would be plain text and the button would stay blocked forever, and v-if instead of :disabled would hide the button completely. Now the form state.

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

const form = reactive({
  name: '',
  year: null,
  engineer: ''
})

const errors = reactive({
  name: '',
  year: '',
  engineer: ''
})

reactive creates a reactive object whose fields you access without .value. The form object holds the field values, and errors holds the messages, where an empty string means no error. Next come the validation functions.

function validateName() {
  if (!form.name) {
    errors.name = 'Name is required'
  } else if (form.name.length < 3) {
    errors.name = 'Name must be at least 3 characters'
  } else {
    errors.name = ''
  }
}

function validateYear() {
  if (!form.year) {
    errors.year = 'Year is required'
  } else if (form.year < 2020 || form.year > 2100) {
    errors.year = 'Year must be between 2020 and 2100'
  } else {
    errors.year = ''
  }
}

function validateEngineer() {
  errors.engineer = form.engineer ? '' : 'Engineer is required'
}

Each function checks one field and sets its message. The order of the conditions matters: first an empty field, then the details, such as the length of the name or the range of years from 2020 to 2100. Finally, the computed and the submit handling.

const isFormValid = computed(() => {
  return form.name && form.year && form.engineer &&
         !errors.name && !errors.year && !errors.engineer
})

function submitForm() {
  validateName()
  validateYear()
  validateEngineer()

  if (isFormValid.value) {
    console.log('Registration:', form)
    alert('Module registered!')
  }
}
</script>

isFormValid recalculates automatically whenever the form data changes, which is why a computed suits this role better than a flag updated by hand. submitForm first runs all the validations, because the operator may have corrected a field and pressed Enter without leaving it, and in that case @blur has not fired yet. Then it reads isFormValid.value - the computed recalculates on that read, so it sees the messages set one line above. The complete flow looks like this: a click on the button, @submit.prevent calls the procedure, validation of all fields, sending the data when it is valid, and finally a success message or a form reset.

When should you validate? I recommend two moments: @blur, when the operator is done with a field, and @submit as the final check. Validating on every @input buries someone who has just started typing under error messages. In the next lesson you will assemble these elements into a complete registration form with field groups and a reset.

Remember: validation is the station's airlock - data moves on only when every sensor confirms it is safe.

Code for this lesson: App.vue
<script setup>
import { ref, computed } from 'vue'

const missionData = ref({
  title: '',
  priority: '',
  budget: '',
  notes: ''
})

const errors = ref({
  title: '',
  priority: '',
  budget: '',
  notes: ''
})

const validateTitle = () => {
  if (!missionData.value.title.trim()) {
    errors.value.title = 'Title is required'
  } else if (missionData.value.title.trim().length < 5) {
    errors.value.title = 'Title must have at least 5 characters'
  } else {
    errors.value.title = ''
  }
}

const validatePriority = () => {
  const num = Number(missionData.value.priority)
  if (isNaN(num) || num < 1 || num > 10) {
    errors.value.priority = 'Priority must be a number from 1 to 10'
  } else {
    errors.value.priority = ''
  }
}

const validateBudget = () => {
  const num = Number(missionData.value.budget)
  if (isNaN(num) || num <= 0) {
    errors.value.budget = 'Budget must be a number greater than 0'
  } else {
    errors.value.budget = ''
  }
}

const validateNotes = () => {
  const trimmed = missionData.value.notes.trim()
  if (trimmed.length > 0 && trimmed.length < 10) {
    errors.value.notes = 'Notes must have at least 10 characters or be empty'
  } else {
    errors.value.notes = ''
  }
}

const isFormValid = computed(() => {
  return !errors.value.title &&
         !errors.value.priority &&
         !errors.value.budget &&
         !errors.value.notes &&
         missionData.value.title.trim() &&
         missionData.value.priority &&
         missionData.value.budget
})

const budgetFormatted = computed(() => {
  if (!missionData.value.budget) return ''
  return `$${Number(missionData.value.budget).toLocaleString()}`
})
</script>

<template>
  <div class="validation-center">
    <div class="center-header">
      <h2>Mission Validation Center</h2>
      <p class="subtitle">v-model Modifiers and Form Validation</p>
    </div>

    <div class="form-container">
      <!-- .trim modifier -->
      <div class="form-group">
        <label for="title">Mission Title (.trim):</label>
        <input
          id="title"
          v-model.trim="missionData.title"
          @blur="validateTitle"
          type="text"
          placeholder="e.g. Gale Crater Exploration"
          class="form-input"
          :class="{ error: errors.title }"
        />
        <div v-if="errors.title" class="error-message">
          {{ errors.title }}
        </div>
        <div v-else class="help-text">
          Spaces at the beginning and end will be removed automatically
        </div>
      </div>

      <!-- .number modifier -->
      <div class="form-group">
        <label for="priority">Mission Priority (.number):</label>
        <input
          id="priority"
          v-model.number="missionData.priority"
          @blur="validatePriority"
          type="text"
          placeholder="1-10"
          class="form-input"
          :class="{ error: errors.priority }"
        />
        <div v-if="errors.priority" class="error-message">
          {{ errors.priority }}
        </div>
        <div v-else class="help-text">
          Value automatically converted to a number
        </div>
        <div class="type-display">
          Data type: <code>{{ typeof missionData.priority }}</code>
        </div>
      </div>

      <!-- .number with formatting -->
      <div class="form-group">
        <label for="budget">Mission Budget (.number):</label>
        <input
          id="budget"
          v-model.number="missionData.budget"
          @blur="validateBudget"
          type="text"
          placeholder="e.g. 1000000"
          class="form-input"
          :class="{ error: errors.budget }"
        />
        <div v-if="errors.budget" class="error-message">
          {{ errors.budget }}
        </div>
        <div v-else-if="missionData.budget" class="success-text">
          Formatted budget: {{ budgetFormatted }}
        </div>
      </div>

      <!-- .lazy modifier -->
      <div class="form-group">
        <label for="notes">Notes (.lazy):</label>
        <textarea
          id="notes"
          v-model.lazy="missionData.notes"
          @change="validateNotes"
          placeholder="Additional information... (updates on blur)"
          class="form-textarea"
          :class="{ error: errors.notes }"
          rows="4"
        ></textarea>
        <div v-if="errors.notes" class="error-message">
          {{ errors.notes }}
        </div>
        <div v-else class="help-text">
          Data updates only after leaving the field (blur/change)
        </div>
      </div>

      <div class="validation-summary" :class="{ valid: isFormValid }">
        <div v-if="isFormValid" class="valid-message">
          Form is valid and ready to submit!
        </div>
        <div v-else class="invalid-message">
          Form contains errors or incomplete data
        </div>
      </div>
    </div>

    <div class="data-preview">
      <h3>Mission Data Preview</h3>
      <div class="preview-container">
        <div class="preview-item">
          <span class="preview-label">Title:</span>
          <span class="preview-value">{{ missionData.title || '(empty)' }}</span>
        </div>
        <div class="preview-item">
          <span class="preview-label">Priority:</span>
          <span class="preview-value">
            {{ missionData.priority || '(empty)' }}
            (type: {{ typeof missionData.priority }})
          </span>
        </div>
        <div class="preview-item">
          <span class="preview-label">Budget:</span>
          <span class="preview-value">
            {{ missionData.budget || '(empty)' }}
            (type: {{ typeof missionData.budget }})
          </span>
        </div>
        <div class="preview-item">
          <span class="preview-label">Notes:</span>
          <span class="preview-value">{{ missionData.notes || '(empty)' }}</span>
        </div>
      </div>
    </div>

    <div class="modifiers-reference">
      <h3>v-model Modifiers:</h3>
      <div class="modifier-cards">
        <div class="modifier-card">
          <h4>.lazy</h4>
          <p>Synchronizes data on the 'change' event instead of 'input'</p>
          <code>v-model.lazy="variable"</code>
        </div>
        <div class="modifier-card">
          <h4>.number</h4>
          <p>Automatically converts the value to Number</p>
          <code>v-model.number="variable"</code>
        </div>
        <div class="modifier-card">
          <h4>.trim</h4>
          <p>Automatically removes whitespace from the beginning and end</p>
          <code>v-model.trim="variable"</code>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.validation-center {
  background: linear-gradient(135deg, #0a0e27 0%, #1a1e3f 100%);
  color: #00ff88;
  padding: 30px;
  border-radius: 15px;
  border: 2px solid #00b4d8;
  font-family: 'Courier New', monospace;
  max-width: 900px;
  margin: 0 auto;
}

.center-header {
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #00b4d8;
}

.center-header h2 {
  color: #00ff88;
  margin: 0 0 10px 0;
  font-size: 28px;
  text-shadow: 0 0 10px #00ff88;
}

.subtitle {
  color: #00b4d8;
  margin: 0;
  font-size: 14px;
}

.form-container {
  margin-bottom: 30px;
}

.form-group {
  margin-bottom: 25px;
}

.form-group label {
  display: block;
  color: #00b4d8;
  margin-bottom: 10px;
  font-size: 14px;
  font-weight: bold;
}

.form-input,
.form-textarea {
  width: 100%;
  background: rgba(0, 180, 216, 0.1);
  border: 2px solid #00b4d8;
  border-radius: 8px;
  padding: 12px 15px;
  color: #00ff88;
  font-size: 16px;
  font-family: 'Courier New', monospace;
  box-sizing: border-box;
  transition: all 0.3s ease;
}

.form-input:focus,
.form-textarea:focus {
  outline: none;
  border-color: #00ff88;
  box-shadow: 0 0 15px rgba(0, 255, 136, 0.3);
}

.form-input.error,
.form-textarea.error {
  border-color: #ff6b35;
  background: rgba(255, 107, 53, 0.05);
}

.form-textarea {
  resize: vertical;
}

.error-message {
  margin-top: 8px;
  color: #ff6b35;
  font-size: 12px;
  padding: 8px 12px;
  background: rgba(255, 107, 53, 0.1);
  border-radius: 4px;
  border-left: 3px solid #ff6b35;
}

.help-text {
  margin-top: 8px;
  color: #00b4d8;
  font-size: 12px;
  padding: 8px 12px;
  background: rgba(0, 180, 216, 0.05);
  border-radius: 4px;
}

.success-text {
  margin-top: 8px;
  color: #00ff88;
  font-size: 12px;
  padding: 8px 12px;
  background: rgba(0, 255, 136, 0.1);
  border-radius: 4px;
  font-weight: bold;
}

.type-display {
  margin-top: 8px;
  color: #9d4edd;
  font-size: 11px;
}

.type-display code {
  background: rgba(157, 78, 221, 0.2);
  padding: 2px 6px;
  border-radius: 4px;
  color: #9d4edd;
}

.validation-summary {
  padding: 20px;
  background: rgba(255, 107, 53, 0.1);
  border: 2px solid #ff6b35;
  border-radius: 8px;
  text-align: center;
  font-weight: bold;
  transition: all 0.3s ease;
}

.validation-summary.valid {
  background: rgba(0, 255, 136, 0.1);
  border-color: #00ff88;
}

.valid-message {
  color: #00ff88;
  font-size: 16px;
}

.invalid-message {
  color: #ff6b35;
  font-size: 16px;
}

.data-preview {
  margin-bottom: 30px;
}

.data-preview h3 {
  color: #00ff88;
  margin-bottom: 15px;
}

.preview-container {
  background: rgba(0, 0, 0, 0.3);
  border: 1px solid #00b4d8;
  border-radius: 8px;
  padding: 20px;
}

.preview-item {
  padding: 10px 0;
  border-bottom: 1px solid rgba(0, 180, 216, 0.2);
  display: flex;
  justify-content: space-between;
  gap: 15px;
}

.preview-item:last-child {
  border-bottom: none;
}

.preview-label {
  color: #00b4d8;
  font-weight: bold;
}

.preview-value {
  color: #00ff88;
  text-align: right;
  word-break: break-word;
}

.modifiers-reference {
  background: rgba(0, 255, 136, 0.05);
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #00ff88;
}

.modifiers-reference h3 {
  color: #00ff88;
  margin-top: 0;
}

.modifier-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
}

.modifier-card {
  background: rgba(0, 180, 216, 0.1);
  padding: 15px;
  border-radius: 8px;
  border: 1px solid #00b4d8;
}

.modifier-card h4 {
  color: #00ff88;
  margin: 0 0 10px 0;
}

.modifier-card p {
  color: #00b4d8;
  font-size: 12px;
  margin: 0 0 10px 0;
}

.modifier-card code {
  display: block;
  background: rgba(0, 0, 0, 0.3);
  padding: 8px;
  border-radius: 4px;
  color: #00ff88;
  font-size: 11px;
}
</style>

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. How do you create a select with the ability to choose multiple options?

  2. 2. Why is computed good for checking if a form is valid?

These are 2 of 4 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Add validation on @blur with error messages and a computed isFormValid.

  • Vertical ordering

    Arrange the form validation steps from top to bottom:

  • Click in order

    Arrange the syntax for a button with dynamic disabled:

  • Code editor

    Build a select with v-for rendering options from an array of objects and display the selected value.

  • Vertical ordering

    Arrange the correct form submit flow:

  1. QuestionMulti-select
  2. QuestionComputed for validation
  3. Coding taskPractice: Form validation
  4. Put in orderForm validation steps
  5. QuestionDisabled button in a form
  6. Click in orderBuilding :disabled binding
  7. Coding taskPractice: Dynamic select options
  8. QuestionWhen to validate a form
  9. Put in orderForm submit flow

Useful articles