Forms are how the user enters data into an application, and in Colmena Bookings they are at the centre of everything: without a booking form, there are no bookings. In Data Binding you saw v-model on a single text field and discovered that it is :value plus an input event. In this lesson you will apply it to every type of form control (text areas, checkboxes, radio buttons, and single and multiple drop-down lists), you will learn to bind values that are not strings, to use its modifiers and to manage the complete life cycle of a form: submission, validation, accessible error messages and resetting. With all of this we will build the first version of Colmena's booking form, which will calculate the price, validate the data and create a booking object following the course's data model.

Contents

  1. v-model on each type of control
  2. Text fields and text areas
  3. Checkboxes: boolean and array
  4. Radio buttons
  5. Single and multiple drop-down lists
  6. Dynamic options with v-for
  7. Binding values that are not strings: true-value, false-value and :value
  8. Modifiers: .lazy, .number and .trim
  9. Submitting a form with @submit.prevent
  10. Manual validation with computed properties
  11. Resetting the form
  12. Basic form accessibility
  13. Case study: Colmena's booking form

  1. v-model on each type of control

v-model adapts to the element you put it on: depending on the control, it uses a different DOM property and event.

Control Property it binds Event it listens for Usual value type
<input type="text"> (and email, search, date, time...) value input String
<textarea> value input String
<input type="checkbox"> checked change Boolean or array
<input type="radio"> checked change The value of the chosen option
<select> value change The value of the chosen option (or an array with multiple)

One rule common to all of them: v-model ignores the initial value, checked and selected HTML attributes. The script's state is the single source of truth, so the initial value is always defined in the ref or the reactive.

  1. Text fields and text areas

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

const member = ref('')
const notes = ref('')
</script>

<template>
  <label for="member">Name</label>
  <input id="member" v-model="member" type="text" autocomplete="name" />

  <label for="notes">Notes</label>
  <textarea id="notes" v-model="notes" rows="3"></textarea>
  <p>{{ notes.length }} / 300 characters</p>
</template>
  • Every text-type <input> (text, email, password, search, tel, url) works in the same way. So do date and time, which deliver strings in a fixed format: '2026-11-03' and '10:00'.
  • In a <textarea>, the content is always bound with v-model. Interpolation, <textarea>{{ notes }}</textarea>, does not work.
  • Strings may contain line breaks; to display them with the lines preserved, use the CSS property white-space: pre-line on the element where you render them.

  1. Checkboxes: boolean and array

A checkbox can be bound in two ways, depending on the type of the data.

To a boolean: a standalone checkbox that means yes/no.

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

const acceptsRules = ref(false)
</script>

<template>
  <input id="rules" v-model="acceptsRules" type="checkbox" />
  <label for="rules">I accept the room usage rules</label>
  <p>Accepted? {{ acceptsRules }}</p> <!-- true / false -->
</template>

To an array: a group of checkboxes that share the same v-model. Each checkbox has its own value, and the array contains the values of the ticked checkboxes:

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

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

<template>
  <input id="extra-coffee" v-model="extraEquipment" type="checkbox" value="coffee" />
  <label for="extra-coffee">Coffee service</label>

  <input id="extra-water" v-model="extraEquipment" type="checkbox" value="water" />
  <label for="extra-water">Water and glasses</label>

  <p>{{ extraEquipment }}</p> <!-- e.g. [ "water", "coffee" ] -->
</template>
  • When a checkbox is ticked, Vue adds its value to the array; when it is unticked, Vue removes it.
  • The order of the array is the order in which they were ticked, not the order of the checkboxes.
  • For this to work, the initial data must be an array (even if it is empty). If it were a boolean, all the checkboxes would be ticked and unticked together.

  1. Radio buttons

Radio buttons in the same group share a v-model, and the data takes the value of whichever one is selected:

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

const status = ref('confirmed')
</script>

<template>
  <fieldset>
    <legend>Booking status</legend>

    <input id="status-confirmed" v-model="status" type="radio" value="confirmed" />
    <label for="status-confirmed">Confirm now</label>

    <input id="status-pending" v-model="status" type="radio" value="pending" />
    <label for="status-pending">Leave pending</label>
  </fieldset>
  <p>Status: {{ status }}</p>
</template>
  • Because the initial value is 'confirmed', the first option appears selected (there is no need for the checked attribute, which v-model would ignore).
  • With v-model you do not need the name attribute to group the buttons: the shared data groups them. Even so, adding it does no harm and helps keyboard navigation in some browsers.
  • <fieldset> and <legend> group related controls and give the group a title, which is important for accessibility (section 12).

  1. Single and multiple drop-down lists

Single drop-down list: the data takes the value of the chosen option.

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

const roomId = ref('')
</script>

<template>
  <label for="room">Room</label>
  <select id="room" v-model="roomId">
    <option disabled value="">Choose a room</option>
    <option value="panal">Panal Room</option>
    <option value="polen">Polen Room</option>
    <option value="nectar">Néctar Room</option>
  </select>
</template>

Notice the first option: disabled and with an empty value. If the data's initial value does not match any option, the <select> is left in an "unselected" state, and on iOS that prevents the first option from being chosen (the change event does not fire). The disabled empty option avoids the problem and acts as a prompt for the user.

Multiple drop-down list: with the multiple attribute, the data must be an array:

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

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

<template>
  <label for="extras">Extra equipment (Ctrl or ⌘ + click to choose several)</label>
  <select id="extras" v-model="extraEquipment" multiple>
    <option value="coffee">Coffee service</option>
    <option value="water">Water and glasses</option>
    <option value="cabling">HDMI and USB-C adapters</option>
  </select>
</template>

It collects the same information as the group of checkboxes in section 3. Checkboxes are easier to use (they do not require key combinations, especially on mobile devices) when there are few options; the multiple drop-down list saves space when there are many.

  1. Dynamic options with v-for

Options are hardly ever written by hand: they are generated from the data with what you learnt in List Rendering:

<script setup>
import { ref } from 'vue'
import { rooms } from '@/data/rooms.js'

const roomId = ref('panal')
</script>

<template>
  <select id="room" v-model="roomId">
    <option
      v-for="room in rooms"
      :key="room.id"
      :value="room.id"
      :disabled="!room.available"
    >
      {{ room.name }} ({{ room.capacity }} people)
    </option>
  </select>
</template>
  • :value="room.id": what is stored in roomId is the id; what the user sees is the option's text.
  • :disabled="!room.available": the Enjambre Auditorium appears, but cannot be chosen.

The same approach works for generating groups of checkboxes or radio buttons from an array.

  1. Binding values that are not strings: true-value, false-value and :value

By default, a standalone checkbox gives true/false, and the values of checkboxes, radio buttons and options are strings. You can change this.

true-value and false-value define which value the data takes when a standalone checkbox is ticked and unticked:

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

const reminder = ref('yes')
</script>

<template>
  <input
    id="reminder"
    v-model="reminder"
    type="checkbox"
    true-value="yes"
    false-value="no"
  />
  <label for="reminder">Send me a reminder</label>
  <p>{{ reminder }}</p> <!-- 'yes' or 'no' -->
</template>

This is useful when an API expects specific values instead of booleans. Bear in mind that, if the checkbox is unticked when a classic HTML form is submitted, the browser sends nothing: these attributes only affect Vue's data. They also support dynamic binding: :true-value="yesValue".

:value with any data type: with v-bind, the value of an option, checkbox or radio button can be a number, a boolean or even an object:

<script setup>
import { ref } from 'vue'
import { rooms } from '@/data/rooms.js'

const chosenRoom = ref(null)
</script>

<template>
  <select v-model="chosenRoom">
    <option disabled :value="null">Choose a room</option>
    <option v-for="room in rooms" :key="room.id" :value="room">{{ room.name }}</option>
  </select>
  <p v-if="chosenRoom">Capacity: {{ chosenRoom.capacity }}</p>
</template>

Here chosenRoom contains the whole room object, not a string. It is convenient, but in a form that is going to generate a record (such as a booking) it is preferable to store the identifier (roomId), which is what the data model needs and what would be sent to a server. In Colmena we will use ids.

  1. Modifiers: .lazy, .number and .trim

Modifier What it does Example use
.lazy Syncs on the change event (when leaving the field or pressing Enter) instead of on every keystroke (input) Fields whose value triggers expensive calculations or validations that should not appear halfway through typing
.number Converts the text to a number with parseFloat. If it cannot be converted, it leaves the original string Quantities in text fields
.trim Removes spaces at the beginning and end Names, email addresses, searches
<input v-model.trim="member" />
<input v-model.number="attendees" type="number" min="1" />
<textarea v-model.lazy="notes"></textarea>

Important details:

  • .number is applied automatically on <input type="number">. Even so, writing it makes the intention clear. Watch out: if the field is left empty, the value is the empty string '', not 0 or null. Your validation must allow for this.
  • Without .number, an <input type="text"> always gives strings: '4' + 1 would be '41'.
  • They can be combined: v-model.trim.lazy="member".
  • With .trim, the field is not visually "cleaned up" while you type: the data is stored trimmed and the field is updated when it loses focus.

  1. Submitting a form with @submit.prevent

Group the fields inside a <form> element and listen for its submit event:

<form @submit.prevent="submitBooking">
  <!-- fields -->
  <button type="submit">Book</button>
</form>
  • .prevent stops the browser's default behaviour, which is to submit the form and reload the page, which in an SPA would wipe everything out (you saw this in Event Handling).
  • Listening for submit on the form, rather than click on the button, has an advantage: submission also works when Enter is pressed in any text field, as users expect.
  • Buttons inside a <form> are of type submit by default. For a button that must not submit (such as "Reset"), specify type="button".

  1. Manual validation with computed properties

Validating means checking that the data meets the rules before accepting it. With what you already know, the cleanest technique is a computed property that returns an object of errors per field:

const errors = computed(() => {
  const result = {}
  if (form.member === '') {
    result.member = 'Tell us who is making the booking.'
  }
  if (form.attendees < 1) {
    result.attendees = 'Enter at least 1 attendee.'
  }
  return result
})

const formIsValid = computed(() => Object.keys(errors.value).length === 0)
  • Each rule adds a property with the field name and the message. A field without an error does not appear.
  • formIsValid is true if the object is empty.
  • Because they are computed properties, they recalculate themselves as soon as any field changes: there is no need to call any "validate" function.

In the template, the message is displayed next to its field and the button is disabled while there are errors:

<input id="member" v-model.trim="form.member" />
<p v-if="errors.member" class="error">{{ errors.member }}</p>

<button type="submit" :disabled="!formIsValid">Book</button>

10.1 Not showing errors too early

Showing "Tell us who is making the booking" as soon as the page loads, before the user has typed anything, comes across as aggressive. The usual approach is to show a field's error once the user has touched it (has left it) or has tried to submit. This is achieved by keeping track of which fields have been touched:

const touched = reactive({})

function markTouched(field) {
  touched[field] = true
}

function visibleError(field) {
  return touched[field] ? errors.value[field] : ''
}
<input id="member" v-model.trim="form.member" @blur="markTouched('member')" />
<p v-if="visibleError('member')" class="error">{{ visibleError('member') }}</p>

The blur event fires when the field loses focus. The validation (errors) is always up to date; only its display waits until the user has been through the field.

10.2 The browser's native validation

The HTML attributes required, min, max or type="email" activate the browser's native validation, which shows its own bubbles on submission. Combining it with Vue validation produces duplicated messages with different styles. That is why, when you validate with Vue, you add novalidate to the <form>: it turns off the bubbles, but the attributes are still useful as hints for the mobile keyboard and for screen readers. Remember, too, that validation in the browser is a convenience for the user, not a security measure: a real server must validate everything again.

  1. Resetting the form

After a successful submission, the form should return to its initial state. With a reactive, remember what you saw in Reactivity: ref and reactive: it cannot be reassigned. The recommended pattern is a function that creates the initial state and Object.assign to copy it in:

function createEmptyForm() {
  return { member: '', attendees: 1, extraEquipment: [] }
}

const form = reactive(createEmptyForm())

function resetForm() {
  Object.assign(form, createEmptyForm())
}
  • The function returns a new object every time, with new arrays. If you used a constant with the initial values, the extraEquipment array would be shared and, after the first submission, the initial "template" would have been modified.
  • Object.assign replaces the properties of the existing reactive proxy, so the template stays connected.

  1. Basic form accessibility

An accessible form can be used with a keyboard and with a screen reader. The minimum:

Practice How Why
Every control has its label <label for="member"> + id="member" (or the control inside the <label>) The screen reader announces the label on reaching the field, and clicking the label focuses the control
Groups with a title <fieldset> + <legend> for checkboxes and radio buttons The screen reader announces "Booking status, group" before the options
Marking the invalid field :aria-invalid="visibleError('member') ? 'true' : 'false'" The screen reader announces "invalid" on entering the field
Associating the error message :aria-describedby="visibleError('member') ? 'error-member' : null" on the control and id="error-member" on the message The screen reader reads the error message together with the label
Not relying on colour alone Visible error text, not just a red border People with colour blindness may not be able to tell the colour apart
A real submit button <button type="submit"> It works with Enter and with assistive technologies

Remember what you saw in Data Binding: null removes the attribute, so aria-describedby only appears when there is an error to describe.

  1. Case study: Colmena's booking form

We are going to add the first version of the booking form to App.vue. It will collect the room, date, start time, end time, member, attendees, status, extra equipment and notes; it will calculate the estimated price; it will validate that the end time is later than the start time and that the attendees do not exceed the capacity, among other rules; and, on submission, it will create a booking object following the course's data model and add it to a list of bookings.

13.1 The script

Add these pieces at the end of the <script setup> of src/App.vue (the ref, reactive and computed imports already exist). The order matters: createEmptyForm reads selectedRoomId and seats, and it runs as soon as form is created, so those constants have to be declared beforehand:

// --- Booking form ---
const dayHours = Array.from({ length: 13 }, (_, i) => `${String(8 + i).padStart(2, '0')}:00`)
// ['08:00', '09:00', ..., '20:00']

const availableExtras = [
  { value: 'coffee', label: 'Coffee service' },
  { value: 'water', label: 'Water and glasses' },
  { value: 'cabling', label: 'HDMI and USB-C adapters' }
]

// Local date in 'YYYY-MM-DD' format (the same one <input type="date"> uses)
function toISODate(date) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}
const todayISO = toISODate(today)

// '10:30' → 630 minutes since midnight
function toMinutes(time) {
  const [hours, minutes] = time.split(':').map(Number)
  return hours * 60 + minutes
}

function createEmptyForm() {
  return {
    roomId: selectedRoomId.value, // starts from the room selected in the catalogue
    date: '',
    startTime: '10:00',
    endTime: '12:00',
    member: '',
    attendees: Math.max(1, seats.booked),
    status: 'confirmed',
    extraEquipment: [],
    notes: '',
    acceptsRules: false
  }
}

const form = reactive(createEmptyForm())
const touched = reactive({})
const bookings = ref([])

const formRoom = computed(() => rooms.find((room) => room.id === form.roomId))
const durationHours = computed(
  () => (toMinutes(form.endTime) - toMinutes(form.startTime)) / 60
)
const bookingPrice = computed(() =>
  durationHours.value > 0 ? formRoom.value.hourlyPrice * durationHours.value : 0
)

const errors = computed(() => {
  const result = {}
  const room = formRoom.value

  if (form.member === '') {
    result.member = 'Tell us who is making the booking.'
  }
  if (!room.available) {
    result.roomId = `The ${room.name} is not available.`
  }
  if (form.date === '') {
    result.date = 'Choose a date.'
  } else if (form.date < todayISO) {
    result.date = 'The date cannot be earlier than today.'
  }
  if (durationHours.value <= 0) {
    result.endTime = 'The end time must be later than the start time.'
  }
  if (!Number.isInteger(form.attendees) || form.attendees < 1) {
    result.attendees = 'Enter a whole number of attendees, at least 1.'
  } else if (form.attendees > room.capacity) {
    result.attendees = `The ${room.name} holds a maximum of ${room.capacity} people.`
  }
  if (form.notes.length > 300) {
    result.notes = 'Notes cannot exceed 300 characters.'
  }
  if (!form.acceptsRules) {
    result.acceptsRules = 'You must accept the usage rules.'
  }
  return result
})

const formIsValid = computed(() => Object.keys(errors.value).length === 0)
const errorCount = computed(() => Object.keys(errors.value).length)

function markTouched(field) {
  touched[field] = true
}

function visibleError(field) {
  return touched[field] ? errors.value[field] : ''
}

function roomNameById(id) {
  return rooms.find((room) => room.id === id)?.name ?? id
}

function resetForm() {
  Object.assign(form, createEmptyForm())
  for (const field in touched) {
    touched[field] = false
  }
}

function submitBooking() {
  if (!formIsValid.value) return // extra defence: the button is already disabled

  // booking object following the course's data model
  // (plus two optional fields specific to the form: extraEquipment and notes)
  const booking = {
    id: crypto.randomUUID(),
    roomId: form.roomId,
    date: form.date,
    startTime: form.startTime,
    endTime: form.endTime,
    member: form.member,
    attendees: form.attendees,
    status: form.status,
    extraEquipment: [...form.extraEquipment],
    notes: form.notes
  }

  bookings.value.push(booking)
  console.log('[Colmena] Booking created:', booking)
  resetForm()
}

Let's go over the decisions:

  • dayHours generates the coworking space's 13 opening hours (from 08:00 to 20:00). Array.from({ length: 13 }, ...) creates an array with 13 positions and the function calculates each value; padStart(2, '0') turns 8 into '08'.
  • toISODate produces the local date in the same format as <input type="date">. We do not use toISOString() because it works in UTC and, close to midnight, would return the wrong day. Because the format is YYYY-MM-DD, comparing two dates as strings (form.date < todayISO) works correctly.
  • toMinutes converts a time into minutes so that times can be subtracted. durationHours is the difference in hours: negative or zero if the time slot makes no sense.
  • createEmptyForm is the factory for the initial state. It reads the room selected in the catalogue and the booked seats, so the form starts with what the user had already chosen above.
  • form is a reactive: a group of data that always goes together and that we never reassign (it is reset with Object.assign). This is exactly the use case we recommended for reactive.
  • errors concentrates all the rules. The two required by the brief are durationHours <= 0 (the end time must be later than the start time) and attendees > room.capacity. Notice the Number.isInteger check: with an empty numeric field, .number leaves the string '', which is not an integer.
  • submitBooking builds the booking with the model's exact names (id, roomId, date, startTime, endTime, member, attendees, status). crypto.randomUUID() generates a unique identifier (available in modern browsers on localhost and on HTTPS sites). We copy extraEquipment with [...] so that the booking has its own array, disconnected from the form.
  • bookings is a ref holding an array: push is a mutating method that Vue detects (you saw this in 02-08). For now the bookings live only in memory; in module 5 they will move into a store and be sent to the simulated API src/api/bookings.js.

13.2 The form template

Add this section inside <main>, after .selection and before <RoomCard />:

<section class="booking">
  <h2>New booking</h2>

  <form novalidate @submit.prevent="submitBooking">
    <!-- Member -->
    <div class="field">
      <label for="booking-member">Member name</label>
      <input
        id="booking-member"
        v-model.trim="form.member"
        type="text"
        autocomplete="name"
        placeholder="e.g. Laura Gómez"
        :aria-invalid="visibleError('member') ? 'true' : 'false'"
        :aria-describedby="visibleError('member') ? 'error-member' : null"
        @blur="markTouched('member')"
      />
      <p v-if="visibleError('member')" id="error-member" class="error">
        {{ visibleError('member') }}
      </p>
    </div>

    <!-- Room: select with dynamic options -->
    <div class="field">
      <label for="booking-room">Room</label>
      <select
        id="booking-room"
        v-model="form.roomId"
        :aria-invalid="visibleError('roomId') ? 'true' : 'false'"
        :aria-describedby="visibleError('roomId') ? 'error-room' : null"
        @blur="markTouched('roomId')"
      >
        <option v-for="room in rooms" :key="room.id" :value="room.id" :disabled="!room.available">
          {{ room.name }} · {{ room.capacity }} people · {{ formatPrice(room.hourlyPrice) }}/h
        </option>
      </select>
      <p v-if="visibleError('roomId')" id="error-room" class="error">
        {{ visibleError('roomId') }}
      </p>
    </div>

    <!-- Date -->
    <div class="field">
      <label for="booking-date">Date</label>
      <input
        id="booking-date"
        v-model="form.date"
        type="date"
        :min="todayISO"
        :aria-invalid="visibleError('date') ? 'true' : 'false'"
        :aria-describedby="visibleError('date') ? 'error-date' : null"
        @blur="markTouched('date')"
      />
      <p v-if="visibleError('date')" id="error-date" class="error">
        {{ visibleError('date') }}
      </p>
    </div>

    <!-- Time slot: two selects generated with v-for -->
    <div class="field field--times">
      <div>
        <label for="booking-start">Start time</label>
        <select id="booking-start" v-model="form.startTime" @blur="markTouched('endTime')">
          <option v-for="hour in dayHours.slice(0, -1)" :key="hour" :value="hour">{{ hour }}</option>
        </select>
      </div>
      <div>
        <label for="booking-end">End time</label>
        <select
          id="booking-end"
          v-model="form.endTime"
          :aria-invalid="visibleError('endTime') ? 'true' : 'false'"
          :aria-describedby="visibleError('endTime') ? 'error-end-time' : null"
          @blur="markTouched('endTime')"
        >
          <option v-for="hour in dayHours.slice(1)" :key="hour" :value="hour">{{ hour }}</option>
        </select>
      </div>
      <p v-if="visibleError('endTime')" id="error-end-time" class="error">
        {{ visibleError('endTime') }}
      </p>
    </div>

    <!-- Attendees: number -->
    <div class="field">
      <label for="booking-attendees">Attendees</label>
      <input
        id="booking-attendees"
        v-model.number="form.attendees"
        type="number"
        min="1"
        :max="formRoom.capacity"
        :aria-invalid="visibleError('attendees') ? 'true' : 'false'"
        :aria-describedby="visibleError('attendees') ? 'error-attendees' : null"
        @blur="markTouched('attendees')"
      />
      <p v-if="visibleError('attendees')" id="error-attendees" class="error">
        {{ visibleError('attendees') }}
      </p>
    </div>

    <!-- Status: radio buttons -->
    <fieldset class="field">
      <legend>Booking status</legend>
      <input id="status-confirmed" v-model="form.status" type="radio" value="confirmed" />
      <label for="status-confirmed">Confirm now</label>
      <input id="status-pending" v-model="form.status" type="radio" value="pending" />
      <label for="status-pending">Leave pending</label>
    </fieldset>

    <!-- Extra equipment: group of checkboxes bound to an array -->
    <fieldset class="field">
      <legend>Extra equipment</legend>
      <template v-for="extra in availableExtras" :key="extra.value">
        <input
          :id="`extra-${extra.value}`"
          v-model="form.extraEquipment"
          type="checkbox"
          :value="extra.value"
        />
        <label :for="`extra-${extra.value}`">{{ extra.label }}</label>
      </template>
    </fieldset>

    <!-- Notes: text area -->
    <div class="field">
      <label for="booking-notes">Notes for reception (optional)</label>
      <textarea
        id="booking-notes"
        v-model.trim="form.notes"
        rows="3"
        :aria-invalid="errors.notes ? 'true' : 'false'"
        aria-describedby="notes-counter"
      ></textarea>
      <p id="notes-counter" :class="{ error: errors.notes }">
        {{ form.notes.length }} / 300 characters
      </p>
    </div>

    <!-- Rules: boolean checkbox -->
    <div class="field">
      <input
        id="booking-rules"
        v-model="form.acceptsRules"
        type="checkbox"
        @change="markTouched('acceptsRules')"
      />
      <label for="booking-rules">I accept the room usage rules</label>
      <p v-if="visibleError('acceptsRules')" class="error">{{ visibleError('acceptsRules') }}</p>
    </div>

    <!-- Summary and actions -->
    <p class="price-summary">
      {{ formRoom.name }} ·
      {{ durationHours > 0 ? `${durationHours} h` : 'invalid time slot' }} ·
      Estimated price: <strong>{{ formatPrice(bookingPrice) }}</strong>
    </p>

    <p v-if="!formIsValid" class="hint">
      {{ errorCount === 1 ? '1 field still needs completing or correcting.' : `${errorCount} fields still need completing or correcting.` }}
    </p>

    <button type="submit" class="button" :disabled="!formIsValid">Book</button>
    <button type="button" class="button" @click="resetForm">Reset</button>
  </form>

  <h3>Bookings created in this session</h3>
  <p v-if="bookings.length === 0">You have not created any bookings yet.</p>
  <ul v-else class="booking-list">
    <li v-for="booking in bookings" :key="booking.id">
      {{ booking.date }} · {{ booking.startTime }}–{{ booking.endTime }} ·
      {{ roomNameById(booking.roomId) }} · {{ booking.attendees }} people ·
      {{ booking.member }} · <em>{{ booking.status }}</em>
    </li>
  </ul>
</section>

The most noteworthy points:

  • Every type of control from the lesson appears once: text with .trim, a dynamic select, date, two time selects, a number with .number, radio buttons, checkboxes bound to an array, a textarea and a boolean checkbox.
  • The times use dayHours.slice(0, -1) for the start (you cannot start at 20:00, closing time) and dayHours.slice(1) for the end (you cannot finish at 08:00). Even so, an end time earlier than the start time can still be chosen: the validation takes care of that.
  • When leaving the start time we mark endTime as touched, because the time-slot error is displayed next to the end time, which is the field the user has to correct.
  • The checkboxes are generated with <template v-for>, because each option consists of two sibling elements (<input> and <label>). The ids are built from the value so that each label points to its checkbox.
  • The ARIA attributes mark the invalid fields and link each one to its message.
  • novalidate turns off the native bubbles; min, max and type still help the mobile keyboard and assistive technologies.
  • The "Book" button is disabled while there are errors, and the hint says how many fields are still missing. Because it is the form's submit button, while it is disabled the form cannot be submitted with Enter either.
  • "Reset" has type="button": without it, it would submit the form.

13.3 Styles

Add this to the <style scoped> of App.vue:

.booking form {
  display: grid;
  gap: 1rem;
  max-width: 520px;
}

.field {
  display: grid;
  gap: 0.3rem;
  margin: 0;
}

.field--times {
  grid-template-columns: 1fr 1fr;
}

.field--times .error {
  grid-column: 1 / -1;
}

fieldset.field {
  display: block;
  padding: 0.75rem;
  border: 1px solid #dddddd;
  border-radius: 6px;
}

.field input:not([type='checkbox']):not([type='radio']),
.field select,
.field textarea {
  padding: 0.5rem;
  border: 1px solid #bbbbbb;
  border-radius: 6px;
  font: inherit;
}

.field [aria-invalid='true'] {
  border-color: #c62828;
}

.error {
  margin: 0;
  color: #c62828;
  font-size: 0.9rem;
}

.hint {
  margin: 0;
  color: #616161;
}

.price-summary {
  padding: 0.75rem;
  border-radius: 6px;
  background: white;
}

The [aria-invalid='true'] selector paints the border red using the accessibility attribute itself: that way the style and the information given to the screen reader can never contradict each other.

13.4 Try it

  1. Select the Polen Room in the catalogue, book 3 seats and click "Reset" in the form: it returns to its initial state, starting from the room and seats chosen above (Polen Room, 3 attendees).
  2. Enter 6 attendees for the Polen Room and leave the field: "The Polen Room holds a maximum of 4 people." appears, the border turns red and the hint counts the errors.
  3. Choose 14:00 to 11:00: the summary says "invalid time slot" and the error appears under the end time. Correct it to 14:00–16:00: the estimated price for Polen becomes €30.00.
  4. Fill everything in correctly and press Enter in the name field: the booking appears in the list, you see the complete object in the console and the form is reset without showing errors on the fields (only the general hint, because it is incomplete again).
  5. With a screen reader (NVDA on Windows, VoiceOver on macOS), go through the form with the Tab key and listen to how the labels, groups and errors are announced.

Common Mistakes and Tips

  • Initialising a group of checkboxes with something that is not an array. They will all be ticked at once. The initial value must be [].
  • Giving the initial value with HTML attributes (value, checked, selected). v-model ignores them; the initial value goes in the script.
  • Forgetting the disabled empty option in a <select> with no valid initial value. On iOS the first option cannot be chosen.
  • Expecting a number from an empty field with .number. You will get ''. Validate it explicitly.
  • Interpolating the content of a <textarea>. It does not work; use v-model.
  • Forgetting .prevent on submit or type="button" on buttons that do not submit. The page reloads or the form is submitted when it should not be.
  • Reassigning the form's reactive to reset it. form = createEmptyForm() disconnects the template. Use Object.assign.
  • Showing every error when the page loads. Wait until the user touches the field.
  • Relying on browser validation for security. It must always be repeated on the server.
  • Tip: keep all the validation rules in a single errors computed property. When the form becomes a component of its own in module 3, you will be able to move it as a whole, and in module 9 extract it into a reusable composable.

Exercises

Exercise 1. Add a member email field to the form (<input type="email">), required and with a minimally valid format (it must contain an @ and a dot after it). Use .trim, show the error when the user leaves the field and add the accessibility attributes. There is no need to include it in the booking object.

Exercise 2. The reception team wants bookings of more than 4 hours always to be left as 'pending' so that they can review them. Make it so that, if durationHours is greater than 4, the "Confirm now" radio button is disabled, the status automatically changes to 'pending' and an explanation is displayed. Would you use a computed property or a watcher to change the status? Why?

Exercise 3. Replace the group of extra equipment checkboxes with a <select multiple> bound to the same form.extraEquipment and check that the rest of the code (submission, resetting) keeps working without changes. Then go back to the checkboxes and explain in one sentence when you would choose each option.

Solutions

Solution 1.

// In createEmptyForm(): add email: ''

// In errors, before the return:
if (form.email === '') {
  result.email = 'Enter an email address.'
} else if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) {
  result.email = 'The email address is not in a valid format.'
}
<div class="field">
  <label for="booking-email">Email</label>
  <input
    id="booking-email"
    v-model.trim="form.email"
    type="email"
    autocomplete="email"
    :aria-invalid="visibleError('email') ? 'true' : 'false'"
    :aria-describedby="visibleError('email') ? 'error-email' : null"
    @blur="markTouched('email')"
  />
  <p v-if="visibleError('email')" id="error-email" class="error">{{ visibleError('email') }}</p>
</div>

The regular expression requires: one or more characters that are neither @ nor whitespace, an @, more characters, a dot and more characters. It is a minimal check, not an exhaustive one (validating email addresses completely is surprisingly complex); the real verification consists of sending an email. type="email" makes mobile devices show a keyboard with an @.

Solution 2.

const needsReview = computed(() => durationHours.value > 4)

watch(needsReview, (needs) => {
  if (needs) {
    form.status = 'pending'
  }
})
<fieldset class="field">
  <legend>Booking status</legend>
  <input
    id="status-confirmed"
    v-model="form.status"
    type="radio"
    value="confirmed"
    :disabled="needsReview"
  />
  <label for="status-confirmed">Confirm now</label>
  <input id="status-pending" v-model="form.status" type="radio" value="pending" />
  <label for="status-pending">Leave pending</label>
  <p v-if="needsReview" class="hint">
    Bookings of more than 4 hours remain pending until reception reviews them.
  </p>
</fieldset>

(Remember to add watch to the vue import if you do not have it already.) Knowing whether a booking needs review is a derived value: a computed property. But changing form.status means modifying state in response to a change, a side effect: that is a job for a watcher. A computed property must never modify other data. As an extra line of defence, submitBooking could force status: needsReview.value ? 'pending' : form.status.

Solution 3.

<div class="field">
  <label for="booking-extras">Extra equipment (Ctrl or ⌘ + click to choose several)</label>
  <select id="booking-extras" v-model="form.extraEquipment" multiple>
    <option v-for="extra in availableExtras" :key="extra.value" :value="extra.value">
      {{ extra.label }}
    </option>
  </select>
</div>

It works without touching the script: both the group of checkboxes and the <select multiple> bind an array of values, so createEmptyForm, submitBooking and resetForm do not notice the difference. This is the advantage of v-model abstracting away the control: the state is the same; only the presentation changes. I would choose checkboxes when there are few options (they are more visible and easier to use on mobile devices) and a <select multiple> when there are many and space is limited.

Conclusion

v-model adapts to each form control: it binds value with input on text fields and text areas, checked with change on checkboxes (to a boolean or, as a group, to an array) and radio buttons, and value with change on single and multiple drop-down lists, whose options are generated with v-for. With true-value/false-value and :value you can bind values that are not strings, including objects, and the .lazy, .number and .trim modifiers adjust when and how the data is synchronised. A complete form is submitted with @submit.prevent, validated with a computed property of errors per field that disables the submit button and whose messages are shown as each field is touched, reset with a factory function and Object.assign, and made accessible with labels, fieldset/legend, aria-invalid and aria-describedby. Colmena Bookings now has the first version of its booking form: it calculates the estimated price, validates the time slot, the capacity and the other rules, and creates booking objects following the course's data model.

With this lesson you complete the basics module, and you only have to open App.vue to see why the next module is necessary: that single file now contains the header with the clock, the catalogue with its filters, its five states and its sorting, the selected room with its spec sheet, seat management, the search box and a booking form with its validation, in hundreds of lines where it is hard to find anything and which we cannot reuse anywhere else; even formatPrice is duplicated between App.vue and RoomCard.vue, and the card still always shows the Panal Room because we do not yet know how to pass data to it. It is time to split the interface into pieces with a clear responsibility (AppHeader, RoomFilters, RoomList, RoomCard, BookingForm...) that communicate with one another, and that is exactly what we will start doing in Introduction to Components.

New edition · October 2026

Vue.js Course

Module 1: Introduction to Vue.js

Module 2: Vue.js Basics

Module 3: Vue.js Components

Module 4: Vue Router

Module 5: State Management with Vuex and Pinia

Module 6: Vue.js Directives

Module 7: Vue.js Plugins

Module 8: Testing in Vue.js

Module 9: Advanced Vue.js Concepts

Module 10: Building and Deploying Vue.js Applications

Module 11: Real-World Vue.js Projects

© Copyright 2026. All rights reserved