JAVASCRIPT
Implementing Reactive Form Validation in Vue 3
Learn to build dynamic and reactive form validation in Vue 3 using the Composition API, providing instant feedback and error messages to users.
// MyForm.vue
<template>
<form @submit.prevent="submitForm">
<div>
<label for="name">Name:</label>
<input type="text" id="name" v-model="formData.name" @blur="validateName" />
<span v-if="errors.name" class="error-message">{{ errors.name }}</span>
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" v-model="formData.email" @blur="validateEmail" />
<span v-if="errors.email" class="error-message">{{ errors.email }}</span>
</div>
<button type="submit" :disabled="!isFormValid">Submit</button>
</form>
</template>
<script setup>
import { ref, reactive, computed } from 'vue';
const formData = reactive({
name: '',
email: '',
});
const errors = reactive({
name: '',
email: '',
});
const validateName = () => {
if (!formData.name.trim()) {
errors.name = 'Name is required.';
} else if (formData.name.trim().length < 3) {
errors.name = 'Name must be at least 3 characters.';
} else {
errors.name = '';
}
};
const validateEmail = () => {
if (!formData.email.trim()) {
errors.email = 'Email is required.';
} else if (!/^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/.test(formData.email)) {
errors.email = 'Invalid email format.';
} else {
errors.email = '';
}
};
const validateAll = () => {
validateName();
validateEmail();
return !errors.name && !errors.email;
};
const isFormValid = computed(() => {
return formData.name.trim() !== '' && !errors.name &&
formData.email.trim() !== '' && !errors.email;
});
const submitForm = () => {
if (validateAll()) {
alert('Form submitted successfully!
' + JSON.stringify(formData, null, 2));
// Proceed with form submission logic (e.g., API call)
} else {
alert('Please correct the form errors.');
}
};
</script>
<style scoped>
.error-message {
color: red;
font-size: 0.9em;
}
</style>
How it works: This snippet demonstrates how to implement reactive form validation in Vue 3 using the Composition API. It uses `reactive` for form data and errors, and `computed` for overall form validity. Validation functions are triggered on blur events or on form submission, providing immediate feedback. This approach offers a clear and organized way to manage form states and error messages.