Advanced Forms — Vue

Validation means checking the form's data before it is sent. Keep the form's data in one reactive object and the warnings (error messages) in errors, with the…

The order form at Mrs. Sri's stall is already bound to its data with v-model. Now the data has to be checked first before it's sent: the name can't be empty, and there must be at least 1 portion. This check is called validation. Picture the cashier taking an order slip. Before passing it to the kitchen, the cashier checks every field and writes a red note next to any wrong one. The cashier only passes the slip to the kitchen when everything is fine. In Vue, the order slip is the form, the red note is the warning that shows under a field, and passing the slip to the kitchen is sending the order. The only question left is when the cashier checks: when the customer gives the slip to the cashier, when the customer finishes one field, or while the customer is still writing.

One form object, one errors object

Keep the form's data in one reactive object. Keep its warnings (the error message for each field) in one errors object. The keys in errors match the field names: the warning for the name field is stored in errors.name.

const initial = { name: "", portions: 1 }
const form = reactive({ ...initial })
const errors = ref({})

function validate() {
  errors.value = {}
  if (!form.name.trim()) errors.value.name = "Name is required"
  if (form.portions < 1) errors.value.portions = "At least 1 portion"
  return Object.keys(errors.value).length === 0
}

function submit() {
  if (!validate()) return
  // safe: send the order to the kitchen
}

---template---
<form @submit.prevent="submit">
  <input v-model.trim="form.name" placeholder="Customer name" />
  <span v-if="errors.name" class="error">{{ errors.name }}</span>

  <input type="number" v-model.number="form.portions" />
  <span v-if="errors.portions" class="error">{{ errors.portions }}</span>

  <button type="submit">Send</button>
</form>
What is sent errors after validate() What shows
empty name, 1 portion { name: "Name is required" } a warning under the name field
name "Sri", 0 portions { portions: "At least 1 portion" } a warning under the portion field
name "Sri", 2 portions {} no warning, the order continues

When to check: on send, on leaving a field, or on every keystroke

There are three times to check, the same three times the cashier can check the order slip:

When How it's written How it feels to the customer
On send validate() inside submit() calm while filling in, every warning appears at once
On leaving a field @blur="leave('name')" a warning appears as soon as they move to the next field
On every keystroke errors as a computed of form instant, but it can be too early

In the first exercise, the form is checked on send: typing alone doesn't change the result of the last send. "Success!" stays even when the name is deleted, until the form is sent again.

When checking on every keystroke, errors is calculated from the data with computed, so errors holds warnings from the moment the page appears. As a result, "Name is required" shows right away, before the customer has touched anything. Red warnings on a form nobody has touched feel like being scolded in advance. The fix: record which fields have been touched, and show warnings only for those fields. In this code, the touched object records the fields that have been touched:

const touched = reactive({ name: false, portions: false })
const errors = computed(() => {
  const e = {}
  if (!form.name.trim()) e.name = "Name is required"
  if (form.portions < 1) e.portions = "At least 1 portion"
  return e
})

---template---
<input v-model="form.name" @blur="touched.name = true" />
<span v-if="touched.name && errors.name" class="error">{{ errors.name }}</span>

Other options for checking a form:

Way When to pick it
Built-in attributes: required, min="1", type="email" simple rules, where the browser's own messages are enough. We tried it in Chromium, Firefox and WebKit: while any field breaks its rule, the submit event doesn't happen, so the submit function isn't called
Your own code, as in this lesson a small form with warnings you write yourself
VeeValidate 4.15.1 or FormKit 2.5.0, with a Zod 4.6.7 or Valibot 1.5.0 schema a big form with many rules. The rules are written once as a schema (a list of rules for each field), and the library tracks touched fields and their warnings

Sending: the button is off while waiting

Sending to a server takes time. If the button can still be pressed, an impatient customer presses it twice, and the kitchen gets the same order twice. This code turns the button off while the order is being sent. Here setTimeout pretends to be a server that answers after 1.5 seconds:

const sending = ref(false)

function submit() {
  if (!validate()) return
  sending.value = true
  setTimeout(() => {          // pretend to wait for the server, 1.5 seconds
    sending.value = false
    Object.assign(form, initial)
  }, 1500)
}

---template---
<button type="submit" :disabled="sending">
  {{ sending ? "Sending..." : "Send" }}
</button>

Emptying the form: Object.assign, not a new object

After the order is sent, the form is emptied again. The way to do it: copy the starting values into the same object. Object.assign(form, initial) copies every property of initial into form:

Object.assign(form, initial)   // form.name becomes "", form.portions becomes 1

Many people first think of making a new object instead, and that is wrong:

Written What happens
const form = reactive(...), then form = reactive({ ...initial }) JavaScript refuses: Assignment to constant variable.
let form = reactive(...), then form = reactive({ ...initial }) it runs, but in the exercise editor the screen and the code no longer match: the field still shows "Sri", while submit() reads the new empty object and answers "Name is required"

Vue tracks that reactive object, the one made first, not the variable's name. If you really want to replace the whole object, keep the form in ref({ ...initial }), then write form.value = { ...initial }.

⚠️ Warnings left behind, warnings too early, and double orders

TL;DR: Validation means checking the form's data before it is sent. Keep the form's data in one reactive object and the warnings (error messages) in errors, with the same keys as the field names: errors.value.name = "Name is required". Start validate() (the function that checks the form) with errors.value = {} so old warnings go away, and call it from @submit.prevent (send without reloading the page). Check on send, on leaving a field (@blur), or on every keystroke (computed). The last way needs touched, a record of the fields the customer has already left, so an empty form doesn't turn red at once. Turn the button off with :disabled="sending" while waiting for the server. Empty the form with Object.assign(form, initial), which copies the starting values into the same object, not with a new object. The v-model modifiers help too: .trim removes spaces at the start and end, .number turns the field's content into a number, and .lazy waits for the change event (when the field is left).

⚡ One form object, one errors object

Write:

function validate() {
  errors.value = {}
  if (!form.name.trim()) errors.value.name = "Name is required"
  if (form.portions < 1) errors.value.portions = "At least 1 portion"
  return Object.keys(errors.value).length === 0
}
Guess first: the line errors.value = {} is deleted. The form is sent with an empty name, then the name is filled in and the form is sent again. Does the warning go away?

No. errors.name from the first send is never removed, so the warning stays on screen, even though the field is now correct.

Meaning: Validation means checking the form's data before it is sent. form is a reactive object holding the form's data, and !form.name.trim() is true when the name is empty. Warnings (error messages) are stored in errors under the same key as their field's name, so the template can show them with v-if="errors.name". validate() returns true when errors is empty, and is called from @submit.prevent.

⚡ .trim removes spaces, .number makes a number

Write:

<input v-model.trim="form.name" placeholder="Customer name" />
<input type="number" v-model.number="form.portions" />

Meaning: .trim and .number are v-model modifiers. .trim removes spaces at the start and end, so a name of only spaces counts as empty. .number turns the field's content into a number, so form.portions < 1 compares numbers.

⚡ The button is off while waiting

Write:

<button type="submit" :disabled="sending">
  {{ sending ? "Sending..." : "Send" }}
</button>

Meaning: :disabled="sending" turns the button off while sending is true, that is, while the order is being sent to the server. A second click doesn't call submit (the function that sends the order) again, so the same order isn't sent twice. The label also changes to "Sending...".

What you will learn