JAVASCRIPT
Basic Reactive Form Validation in Vue 3 Composition API
Implement client-side form validation in Vue 3 using the Composition API, `computed` properties, and reactive state to provide immediate feedback to users.
// App.vue
<template>
<form @submit.prevent="submitForm">
<div>
<label for="username">Username:</label>
<input type="text" id="username" v-model="username" @blur="validateUsername" />
<span v-if="errors.username" class="error">{{ errors.username }}</span>
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" v-model="email" @blur="validateEmail" />
<span v-if="errors.email" class="error">{{ errors.email }}</span>
</div>
<button type="submit" :disabled="!isFormValid">Submit</button>
</form>
</template>
<script setup>
import { ref, reactive, computed } from 'vue';
const username = ref('');
const email = ref('');
const errors = reactive({
username: '',
email: ''
});
const validateUsername = () => {
if (username.value.length < 3) {
errors.username = 'Username must be at least 3 characters.';
} else {
errors.username = '';
}
};
const validateEmail = () => {
if (!/\S+@\S+\.\S+/.test(email.value)) {
errors.email = 'Please enter a valid email address.';
} else {
errors.email = '';
}
};
// Computed property to check if the form is valid overall
const isFormValid = computed(() => {
// Run all validations to ensure all fields are checked initially
// Or check if all error messages are empty
return Object.values(errors).every(error => error === '') && username.value !== '' && email.value !== '';
});
const submitForm = () => {
validateUsername(); // Ensure final validation on submit
validateEmail();
if (isFormValid.value) {
alert('Form submitted successfully!');
// Process form data, e.g., send to API
console.log({ username: username.value, email: email.value });
// Reset form
username.value = '';
email.value = '';
} else {
alert('Please correct the form errors.');
}
};
</script>
<style scoped>
.error {
color: red;
font-size: 0.9em;
}
div {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
}
input[type="text"], input[type="email"] {
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
width: 250px;
}
button {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
</style>
How it works: This snippet demonstrates basic client-side form validation in Vue 3 using the Composition API. It uses `ref` for input values, `reactive` for an errors object, and `computed` for `isFormValid`. Validation functions are triggered on input blur or form submission, updating the `errors` object to provide immediate feedback. The submit button is disabled until all fields are valid, enhancing user experience.