Form validation basics
Validating means checking values as the user types and showing helpful messages before submitting.
In this page:
Syntax
export default {
computed: {
error() {
return this.field ? '' : 'error message';
}
}
}
<p v-if="error">{{ error }}</p>
Form validation basics
A simple approach uses computed properties that return error messages based on the current data, and disables the submit button while there are errors.
For complex forms consider libraries like VeeValidate or Vuelidate. Always validate again on the server.
Note:
Client-side validation is for user experience; the server must still validate.
Example: Form validation basics
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<input v-model="email" placeholder="email">
<span style="color:red">{{ error }}</span>
<button :disabled="!!error">Sign up</button>
</div>
<script>
Vue.createApp({
data() { return { email: "" }; },
computed: {
error() {
if (!this.email) return "Email is required";
return /^\S+@\S+\.\S+$/.test(this.email) ? "" : "Enter a valid email";
},
},
}).mount("#app");
const i = document.querySelector("input");
i.value = "[email protected]"; i.dispatchEvent(new window.Event("input"));
Vue.nextTick(() => console.log("valid email -> button disabled:", document.querySelector("button").disabled));
</script>
</body>
</html>
<!-- Output:
Rendered: Sign up
console: valid email -> button disabled: false
-->
Live Example
Related Topics
Common Mistakes
- Trusting client-side validation only
- Showing errors before the user typed
- Not disabling submit while invalid
Chapter Summary
- Computed properties can produce errors
- Disable submit while invalid
- Libraries help with large forms
- Always validate on the server too
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: