JAVASCRIPT

Basic Form Validation in Vue 3 with Composition API

Implement simple client-side form validation in Vue 3 using the Composition API, reactive references, and computed properties for immediate feedback.

<template>
  <form @submit.prevent="handleSubmit">
    <div>
      <label for="username">Username:</label>
      <input type="text" id="username" v-model="username.value" @blur="validateUsername" />
      <p v-if="username.error" class="error">{{ username.error }}</p>
    </div>
    <div>
      <label for="email">Email:</label>
      <input type="email" id="email" v-model="email.value" @blur="validateEmail" />
      <p v-if="email.error" class="error">{{ email.error }}</p>
    </div>
    <button type="submit" :disabled="!isFormValid">Submit</button>
  </form>
</template>

<script setup>
import { ref, computed } from 'vue';

// Reactive references for form fields and their errors
const username = ref({ value: '', error: '' });
const email = ref({ value: '', error: '' });

// Validation functions
const validateUsername = () => {
  if (!username.value.value) {
    username.value.error = 'Username is required.';
  } else if (username.value.value.length < 3) {
    username.value.error = 'Username must be at least 3 characters.';
  } else {
    username.value.error = '';
  }
};

const validateEmail = () => {
  if (!email.value.value) {
    email.value.error = 'Email is required.';
  } else if (!/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/.test(email.value.value)) {
    email.value.error = 'Invalid email format.';
  } else {
    email.value.error = '';
  }
};

// Computed property to check if the form is valid
const isFormValid = computed(() => {
  // Run all validations to ensure errors are updated
  validateUsername();
  validateEmail();
  return !username.value.error && !email.value.error && username.value.value && email.value.value;
});

const handleSubmit = () => {
  if (isFormValid.value) {
    alert(`Form submitted!
Username: ${username.value.value}
Email: ${email.value.value}`);
    // Proceed with form submission (e.g., API call)
  } else {
    alert('Please correct the form errors.');
  }
};
</script>

<style scoped>
.error {
  color: red;
  font-size: 0.8em;
}
form div {
  margin-bottom: 1em;
}
label {
  display: block;
  margin-bottom: 0.5em;
}
input {
  padding: 0.5em;
  border: 1px solid #ccc;
  border-radius: 4px;
  width: 200px;
}
</style>
How it works: This snippet demonstrates basic client-side form validation in Vue 3 using the Composition API. Each input field's value and its corresponding error message are managed by separate `ref` objects. Validation functions are triggered on `@blur` events to provide immediate feedback. A `computed` property, `isFormValid`, dynamically checks if all fields meet their validation rules. The submit button is disabled until the form is valid. When submitted, `handleSubmit` either processes the data or alerts the user to errors, ensuring a user-friendly experience.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs