Vue.js course ยท Module 5: Events & Forms
Forms in Practice - Module Registration
The NOVA LAB engineering department has received an order: one form in which every new station module gets registered, from the airlock to the laboratory. A module has a name, a type, a year and a status, technical parameters, categories, a description and service options. A dozen fields dumped one under another make a wall that nobody will read. So we will build a form divided into groups, with fields that appear only when they make sense, with a reset and a data preview.
Field groups: fieldset and legend
The <fieldset> element groups related fields, and <legend> is the caption of that group. Screen readers read it out before the fields, so an operator using a screen reader knows which section they are in. A <label> with the for attribute points to the id of a field, so clicking the caption puts the cursor in the field. The first group starts with the module name and type.
<template>
<form @submit.prevent="submitModule" class="module-form" style="background: #0a0e27; color: #00ff88;">
<h2>Mission module registration</h2>
<!-- Basic information -->
<fieldset style="border-color: #00b4d8;">
<legend>Basic information</legend>
<div class="form-group">
<label for="name">Module name *</label>
<input
id="name"
v-model.trim="module.name"
required
minlength="3"
style="background: #1a1e37; color: #00ff88;"
/>
</div>
<div class="form-group">
<label for="type">Type *</label>
<input id="type" v-model.trim="module.type" required style="background: #1a1e37; color: #00ff88;" />
</div>The name has the required and minlength="3" attributes, which is built-in HTML validation. The browser checks such attributes before it even dispatches the submit event, and on an error it shows its own message - @submit.prevent does not switch any of this off. v-model.trim also removes unnecessary spaces. Next comes the row with the year and the status.
<div class="form-row">
<div class="form-group">
<label for="year">Deployment year</label>
<input
id="year"
v-model.number="module.year"
type="number"
min="2020"
max="2100"
style="background: #1a1e37; color: #00ff88;"
/>
</div>
<div class="form-group">
<label for="status">Status</label>
<select id="status" v-model="module.status" style="background: #1a1e37; color: #00ff88;">
<option value="">Select...</option>
<option value="ACTIVE">Active</option>
<option value="STANDBY">Standby</option>
<option value="MAINTENANCE">Maintenance</option>
<option value="OFFLINE">Offline</option>
</select>
</div>
</div>
</fieldset>The year has min and max for the browser and .number for Vue. The isValid computed does not check the year, so an entry of 1999 is stopped only by the browser after the submit button is clicked. The status list starts with an empty option that prompts a choice. The second group shows that v-model also works on nested paths such as module.params.maxPower.
<!-- Parameters -->
<fieldset style="border-color: #00b4d8;">
<legend>Parameters</legend>
<div class="form-row">
<div class="form-group">
<label>Max power (MW)</label>
<input v-model.number="module.params.maxPower" type="number" style="background: #1a1e37; color: #00ff88;" />
</div>
<div class="form-group">
<label>Temperature (K)</label>
<input v-model.number="module.params.temperature" type="number" style="background: #1a1e37; color: #00ff88;" />
</div>
<div class="form-group" v-if="needsPressure">
<label>Pressure (kPa)</label>
<input v-model.number="module.params.pressure" type="number" style="background: #1a1e37; color: #00ff88;" />
</div>
</div>
</fieldset>The pressure field has v-if="needsPressure", so it exists only when the computed returns true. With false, Vue removes it from the DOM rather than just hiding it. Removing the field does not clear the data, though: a pressure typed earlier stays in module.params.pressure. The categories in the third group are generated by v-for from an array.
<!-- Categories -->
<fieldset>
<legend>Categories</legend>
<div class="checkbox-group">
<label v-for="cat in availableCategories" :key="cat.value">
<input
type="checkbox"
v-model="module.categories"
:value="cat.value"
/>
{{ cat.label }}
</label>
</div>
</fieldset>Each checkbox takes its value from :value="cat.value", and all of them write into one array, module.categories, exactly like the checkbox group from the v-model lesson. The fourth group is the description in a text area.
<!-- Description -->
<fieldset>
<legend>Description</legend>
<textarea
v-model="module.description"
rows="4"
placeholder="Describe the mission module..."
></textarea>
<p class="char-count">
{{ module.description.length }} / 500 characters
</p>
</fieldset>The rows="4" attribute sets the visible height of the field. The counter below only reports the length of the description and limits nothing: a hard limit would require the maxlength="500" attribute. The fifth group holds the options and a conditional field.
<!-- Options -->
<fieldset>
<legend>Options</legend>
<label class="checkbox-label">
<input type="checkbox" v-model="module.isActive" />
Module active
</label>
<label class="checkbox-label">
<input type="checkbox" v-model="module.needsMaintenance" />
Requires maintenance
</label>
<div v-if="module.needsMaintenance" class="form-group">
<label>Maintenance budget (USD)</label>
<input v-model.number="module.maintenanceCost" type="number" min="0" />
</div>
</fieldset>This is the conditional field pattern: a checkbox with v-model controls a variable, and v-if on that variable shows an extra field with the maintenance budget. isActive starts as true, so the box is checked from the start, because v-model takes its state from JavaScript. At the end of the template come the buttons and the data preview.
<!-- Buttons -->
<div class="form-actions">
<button type="button" @click="resetForm">Clear</button>
<button type="submit" :disabled="!isValid">Register module</button>
</div>
<!-- Preview -->
<details>
<summary>Data preview</summary>
<pre>{{ JSON.stringify(module, null, 2) }}</pre>
</details>
</form>
</template>type="button" on the clear button is crucial, because a button inside a form has the submit type by default, and without this attribute clearing would submit the form. <details> with <summary> creates an expandable preview, and JSON.stringify(module, null, 2) formats the data with a two-space indent. Let us move on to the script.
<script setup>
import { reactive, computed } from 'vue'
const initialState = {
name: '',
type: '',
year: null,
status: '',
params: { maxPower: null, temperature: null, pressure: null },
categories: [],
description: '',
isActive: true,
needsMaintenance: false,
maintenanceCost: null
}
const module = reactive({
...initialState,
params: { ...initialState.params },
categories: []
})initialState describes the empty form, and reactive turns it into state. Beware of a trap: spreading ...initialState copies only the first level of the object. If params did not get a separate copy, typing in a power value would also change initialState.params, and the reset would restore the typed numbers instead of empty fields. That is why params and categories get copies of their own. Next, the category list and two computed values.
const availableCategories = [
{ value: 'lifesupport', label: 'Life support' },
{ value: 'energy', label: 'Energy' },
{ value: 'research', label: 'Research' },
{ value: 'communication', label: 'Communication' },
{ value: 'navigation', label: 'Navigation' }
]
const needsPressure = computed(() => {
return ['lifesupport', 'research'].some(c => module.categories.includes(c))
})
const isValid = computed(() => {
return module.name.length >= 3 && module.type
})availableCategories is a plain array, because it never changes and needs no reactivity. needsPressure uses the some method, which returns true when at least one element meets the condition. isValid plays the role of isFormValid from the previous lesson: it requires a name of at least three characters and a non-empty type. What remains is the reset and the submission.
function resetForm() {
Object.assign(module, {
...initialState,
params: { ...initialState.params },
categories: []
})
}
function submitModule() {
if (isValid.value) {
console.log('Registering:', JSON.parse(JSON.stringify(module)))
alert('Module has been registered!')
}
}
</script>Object.assign writes the initial values into the existing module object, so the template stays connected to the same state. Replacing the whole object with a new one would cut the template off from the data. params and categories get fresh copies again. JSON.parse(JSON.stringify(module)) gives the console a plain snapshot of the data instead of a reactive object. I recommend going one step further and turning initialState into a function that returns a new object on every call - the shallow copy trap then disappears completely. In the module project you will use the same order: state, v-model, validation on @blur, the isFormValid computed and @submit.prevent.
Remember: a good registration form works like a well-designed station module - every group has its own compartment, and the reset restores the factory settings without leaving a trace.
Code for this lesson: App.vue
<script setup>
import { ref, computed } from 'vue'
const missionForm = ref({
commander: '',
destination: '',
duration: '',
crewSize: '',
missionType: 'exploration',
equipment: [],
emergencyProtocol: false,
launchDate: '',
objectives: ''
})
const errors = ref({})
const submitted = ref(false)
const submittedData = ref(null)
const missionTypes = [
{ value: 'exploration', label: 'Exploration' },
{ value: 'research', label: 'Research' },
{ value: 'construction', label: 'Construction' },
{ value: 'rescue', label: 'Rescue' }
]
const equipmentOptions = [
{ id: 'rover', name: 'Rover' },
{ id: 'drill', name: 'Drill' },
{ id: 'lab', name: 'Laboratory' },
{ id: 'satellite', name: 'Satellite' },
{ id: 'drone', name: 'Drone' }
]
const validateForm = () => {
errors.value = {}
if (!missionForm.value.commander.trim()) {
errors.value.commander = 'Commander is required'
}
if (!missionForm.value.destination.trim()) {
errors.value.destination = 'Destination is required'
}
const duration = Number(missionForm.value.duration)
if (!duration || duration < 1 || duration > 365) {
errors.value.duration = 'Duration: 1-365 days'
}
const crew = Number(missionForm.value.crewSize)
if (!crew || crew < 1 || crew > 50) {
errors.value.crewSize = 'Crew: 1-50 people'
}
if (!missionForm.value.launchDate) {
errors.value.launchDate = 'Launch date is required'
}
if (missionForm.value.objectives.trim().length < 20) {
errors.value.objectives = 'Objectives must have at least 20 characters'
}
return Object.keys(errors.value).length === 0
}
const handleSubmit = () => {
if (validateForm()) {
submitted.value = true
submittedData.value = {
...missionForm.value,
submittedAt: new Date().toLocaleString('en-US')
}
// Submission simulation
setTimeout(() => {
resetForm()
}, 5000)
}
}
const resetForm = () => {
missionForm.value = {
commander: '',
destination: '',
duration: '',
crewSize: '',
missionType: 'exploration',
equipment: [],
emergencyProtocol: false,
launchDate: '',
objectives: ''
}
errors.value = {}
submitted.value = false
submittedData.value = null
}
const isFormValid = computed(() => {
return missionForm.value.commander.trim() &&
missionForm.value.destination.trim() &&
missionForm.value.duration &&
missionForm.value.crewSize &&
missionForm.value.launchDate &&
missionForm.value.objectives.trim().length >= 20
})
</script>
<template>
<div class="mission-control">
<div class="control-header">
<h2>NOVA LAB Mission Control Center</h2>
<p class="subtitle">Complete Mission Registration System</p>
</div>
<div v-if="submitted" class="success-panel">
<div class="success-message">
<h3>Mission Successfully Registered!</h3>
<p>Data has been sent to the NOVA LAB Command Center</p>
</div>
<div class="submitted-data">
<h4>Mission Details:</h4>
<div class="data-grid">
<div><strong>Commander:</strong> {{ submittedData.commander }}</div>
<div><strong>Destination:</strong> {{ submittedData.destination }}</div>
<div><strong>Duration:</strong> {{ submittedData.duration }} days</div>
<div><strong>Crew:</strong> {{ submittedData.crewSize }} people</div>
<div><strong>Type:</strong> {{ missionTypes.find(t => t.value === submittedData.missionType)?.label }}</div>
<div><strong>Equipment:</strong> {{ submittedData.equipment.length }} items</div>
<div><strong>Launch date:</strong> {{ submittedData.launchDate }}</div>
<div><strong>Sent:</strong> {{ submittedData.submittedAt }}</div>
</div>
</div>
<button @click="resetForm" class="reset-btn">
New Mission
</button>
</div>
<form v-else @submit.prevent="handleSubmit" class="mission-form">
<div class="form-section">
<h3>Basic Information</h3>
<div class="form-field">
<label for="commander">Mission Commander:</label>
<input
id="commander"
v-model.trim="missionForm.commander"
type="text"
placeholder="Full name"
class="form-input"
:class="{ error: errors.commander }"
/>
<span v-if="errors.commander" class="error-text">{{ errors.commander }}</span>
</div>
<div class="form-field">
<label for="destination">Destination:</label>
<input
id="destination"
v-model.trim="missionForm.destination"
type="text"
placeholder="e.g. Gale Crater, Mars"
class="form-input"
:class="{ error: errors.destination }"
/>
<span v-if="errors.destination" class="error-text">{{ errors.destination }}</span>
</div>
<div class="form-row">
<div class="form-field">
<label for="duration">Duration (days):</label>
<input
id="duration"
v-model.number="missionForm.duration"
type="number"
placeholder="1-365"
class="form-input"
:class="{ error: errors.duration }"
/>
<span v-if="errors.duration" class="error-text">{{ errors.duration }}</span>
</div>
<div class="form-field">
<label for="crew">Crew size:</label>
<input
id="crew"
v-model.number="missionForm.crewSize"
type="number"
placeholder="1-50"
class="form-input"
:class="{ error: errors.crewSize }"
/>
<span v-if="errors.crewSize" class="error-text">{{ errors.crewSize }}</span>
</div>
</div>
<div class="form-field">
<label for="launch">Launch date:</label>
<input
id="launch"
v-model="missionForm.launchDate"
type="date"
class="form-input"
:class="{ error: errors.launchDate }"
/>
<span v-if="errors.launchDate" class="error-text">{{ errors.launchDate }}</span>
</div>
</div>
<div class="form-section">
<h3>Mission Configuration</h3>
<div class="form-field">
<label>Mission type:</label>
<div class="radio-group">
<label
v-for="type in missionTypes"
:key="type.value"
class="radio-label"
>
<input
v-model="missionForm.missionType"
type="radio"
:value="type.value"
/>
{{ type.label }}
</label>
</div>
</div>
<div class="form-field">
<label>Equipment:</label>
<div class="checkbox-group">
<label
v-for="item in equipmentOptions"
:key="item.id"
class="checkbox-label"
>
<input
v-model="missionForm.equipment"
type="checkbox"
:value="item.id"
/>
{{ item.name }}
</label>
</div>
</div>
<div class="form-field">
<label class="checkbox-label emergency">
<input
v-model="missionForm.emergencyProtocol"
type="checkbox"
/>
Activate Rescue Protocol
</label>
</div>
</div>
<div class="form-section">
<h3>Mission Objectives</h3>
<div class="form-field">
<label for="objectives">Detailed description of objectives:</label>
<textarea
id="objectives"
v-model.trim="missionForm.objectives"
placeholder="Describe the main goals and tasks of the mission (minimum 20 characters)..."
class="form-textarea"
:class="{ error: errors.objectives }"
rows="6"
></textarea>
<div class="char-counter">
Characters: {{ missionForm.objectives.length }}
</div>
<span v-if="errors.objectives" class="error-text">{{ errors.objectives }}</span>
</div>
</div>
<div class="form-actions">
<button
type="submit"
class="submit-btn"
:class="{ disabled: !isFormValid }"
:disabled="!isFormValid"
>
Register Mission
</button>
<button
type="button"
@click="resetForm"
class="cancel-btn"
>
Cancel
</button>
</div>
<div class="form-status" :class="{ valid: isFormValid }">
{{ isFormValid ? 'Form ready to submit' : 'Fill in all required fields' }}
</div>
</form>
</div>
</template>
<style scoped>
.mission-control {
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: 1000px;
margin: 0 auto;
}
.control-header {
text-align: center;
margin-bottom: 30px;
padding-bottom: 20px;
border-bottom: 2px solid #00b4d8;
}
.control-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;
}
.success-panel {
text-align: center;
}
.success-message {
background: rgba(0, 255, 136, 0.1);
border: 2px solid #00ff88;
border-radius: 12px;
padding: 30px;
margin-bottom: 30px;
}
.success-message h3 {
color: #00ff88;
margin: 0 0 10px 0;
font-size: 24px;
}
.success-message p {
color: #00b4d8;
margin: 0;
}
.submitted-data {
background: rgba(0, 180, 216, 0.05);
border: 1px solid #00b4d8;
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
text-align: left;
}
.submitted-data h4 {
color: #00ff88;
margin-top: 0;
}
.data-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 15px;
color: #00b4d8;
}
.data-grid strong {
color: #00ff88;
}
.reset-btn {
background: linear-gradient(135deg, #00b4d8 0%, #0077b6 100%);
color: white;
border: none;
padding: 15px 40px;
border-radius: 8px;
font-size: 16px;
font-weight: bold;
cursor: pointer;
font-family: 'Courier New', monospace;
}
.mission-form {
display: flex;
flex-direction: column;
gap: 30px;
}
.form-section {
background: rgba(0, 180, 216, 0.05);
padding: 25px;
border-radius: 12px;
border: 1px solid #00b4d8;
}
.form-section h3 {
color: #00ff88;
margin: 0 0 20px 0;
font-size: 20px;
}
.form-field {
margin-bottom: 20px;
}
.form-field:last-child {
margin-bottom: 0;
}
.form-field > label {
display: block;
color: #00b4d8;
margin-bottom: 8px;
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;
}
.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;
}
.form-textarea {
resize: vertical;
}
.form-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 15px;
}
.error-text {
display: block;
margin-top: 5px;
color: #ff6b35;
font-size: 12px;
}
.char-counter {
margin-top: 5px;
color: #00b4d8;
font-size: 12px;
}
.radio-group,
.checkbox-group {
display: flex;
flex-direction: column;
gap: 10px;
}
.radio-label,
.checkbox-label {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 15px;
background: rgba(0, 180, 216, 0.05);
border: 1px solid #00b4d8;
border-radius: 6px;
cursor: pointer;
color: #00ff88;
}
.radio-label:hover,
.checkbox-label:hover {
background: rgba(0, 180, 216, 0.15);
}
.checkbox-label.emergency {
background: rgba(255, 107, 53, 0.1);
border-color: #ff6b35;
color: #ff6b35;
font-weight: bold;
}
.form-actions {
display: flex;
gap: 15px;
justify-content: center;
}
.submit-btn,
.cancel-btn {
padding: 15px 40px;
border: none;
border-radius: 8px;
font-size: 16px;
font-weight: bold;
cursor: pointer;
font-family: 'Courier New', monospace;
transition: all 0.3s ease;
}
.submit-btn {
background: linear-gradient(135deg, #00ff88 0%, #00b368 100%);
color: #0a0e27;
}
.submit-btn:hover:not(.disabled) {
transform: translateY(-2px);
box-shadow: 0 5px 20px rgba(0, 255, 136, 0.4);
}
.submit-btn.disabled {
opacity: 0.5;
cursor: not-allowed;
}
.cancel-btn {
background: linear-gradient(135deg, #ff6b35 0%, #d64545 100%);
color: white;
}
.cancel-btn:hover {
transform: translateY(-2px);
box-shadow: 0 5px 20px rgba(255, 107, 53, 0.4);
}
.form-status {
text-align: center;
padding: 15px;
background: rgba(255, 107, 53, 0.1);
border: 2px solid #ff6b35;
border-radius: 8px;
color: #ff6b35;
font-weight: bold;
}
.form-status.valid {
background: rgba(0, 255, 136, 0.1);
border-color: #00ff88;
color: #00ff88;
}
</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. What is the best way to reset a form in Vue?
2. How do you show an additional field only when a checkbox is checked?
These are 2 of 4 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Horizontal ordering
Arrange the syntax for conditionally displaying a field with v-if:
- Code editor
Build a form with fieldset, validation, reset, and submit.
- Horizontal ordering
Arrange the correct syntax for fieldset with legend:
- Click in order
Arrange the syntax for a form with a submit handler:
- Code editor
Build a form with @blur validation, a reset button, and disabled submit.
- Vertical ordering
Arrange the steps for creating a reactive form in Vue:
- Click in order
Arrange the definition of a computed that checks the form:
- Horizontal ordering
Arrange the correct syntax for a textarea with v-model:
Tasks after this lesson
- QuestionForm reset
- QuestionConditional form fields
- Put in orderConditional field syntax
- Coding taskPractice: Complete form
- QuestionHTML form elements
- QuestionFieldset and legend
- Put in orderFieldset syntax
- Click in orderBuilding a form with @submit.prevent
- Coding taskPractice: Form with validation and reset
- Put in orderReactive form structure
- Click in orderBuilding computed isFormValid
- Put in orderTextarea syntax with v-model