JAVASCRIPT
Client-Side Form Validation and Submission in Vue 3
Implement robust client-side form validation in Vue 3 using event handlers and reactive data properties, providing immediate user feedback for a better UX.
<template>
<form @submit.prevent="handleSubmit">
<div>
<label for="name">Name:</label>
<input type="text" id="name" v-model="formData.name" @blur="validateName" />
<p v-if="errors.name" class="error-message">{{ errors.name }}</p>
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" v-model="formData.email" @blur="validateEmail" />
<p v-if="errors.email" class="error-message">{{ errors.email }}</p>
</div>
<button type="submit" :disabled="!isFormValid">Submit</button>
</form>
</template>
<script setup>
import { reactive, computed } from 'vue';
const formData = reactive({
name: '',
email: ''
});
const errors = reactive({
name: '',
email: ''
});
const validateName = () => {
if (!formData.name) {
errors.name = 'Name is required.';
} else if (formData.name.length < 3) {
errors.name = 'Name must be at least 3 characters.';
} else {
errors.name = '';
}
};
const validateEmail = () => {
if (!formData.email) {
errors.email = 'Email is required.';
} else if (!/^[\w.-]+@[\w.-]+\.\w+$/.test(formData.email)) {
errors.email = 'Please enter a valid email address.';
} else {
errors.email = '';
}
};
const isFormValid = computed(() => {
// Run all validations to ensure all error messages are updated
validateName();
validateEmail();
return !errors.name && !errors.email;
});
const handleSubmit = () => {
// Re-run all validations on submit to catch any un-blurred fields
validateName();
validateEmail();
if (isFormValid.value) {
alert('Form submitted successfully!
' + JSON.stringify(formData, null, 2));
// In a real app, you would send formData to an API
// console.log('Submitting:', formData);
} else {
alert('Please correct the errors in the form.');
}
};
</script>
<style scoped>
.error-message {
color: red;
font-size: 0.8em;
margin-top: 5px;
}
</style>
How it works: This snippet demonstrates client-side form validation in Vue 3. It uses `reactive` to manage form data and validation errors. Input fields are bound with `v-model`. Validation functions are called on `blur` events for immediate feedback and also on form submission. A `computed` property `isFormValid` checks if all fields pass validation, enabling or disabling the submit button. The `@submit.prevent` modifier prevents the default browser form submission, allowing custom `handleSubmit` logic.