Error Messages

The form adds an order even when there's no name, or no drink is chosen: an order for nobody. Before adding it, check the fields, and when something's missing, say what, right by the field.

In the JavaScript course, you wrote each message into its element with textContent, and emptied it once the field was right. In Vue, the messages are in the template, and a ref says when to show them:

<script setup>
// ...
const showErrors = ref(false);

function addOrder() {
    if (name.value === "" || drink.value === "") {
        showErrors.value = true;
        return;
    }
    orders.value.push({ id: nextId, name: name.value, drink: drink.value });
    nextId++;
    name.value = "";
    drink.value = "";
    showErrors.value = false;
}
</script>

<template>
    <form @submit.prevent="addOrder">
        <label for="name">Your name</label>
        <input id="name" v-model.trim="name">
        <p v-if="showErrors && name === ''" class="error">Enter your name.</p>
        <!-- ... -->
    </form>
</template>

When a field is empty, addOrder turns the messages on and ends with return, before it adds anything. The name's message shows while showErrors is true and the name is empty. So as soon as the customer types a name, the message disappears, without sending the form again: name changed, and Vue updated the page. Thanks to .trim, a name of only spaces is "" too, so it gets the message as well. And once an order is added, showErrors goes back to false: the fields are empty again, but the next customer hasn't done anything wrong yet.

Instructions

  1. When the form is sent without a name, don't add the order, and show Enter your name. under the name field, in a paragraph with the class error.

  2. Do the same for the drink: Choose a drink. When both are missing, both messages show.