Blog>
Snippets

Reactive Forms with Dynamic Validation

Build a form with Vue 3 where input validation reacts to changes in the input state, displaying errors and enabling form submission when valid.
<template>
  <div>
    <form @submit.prevent="handleSubmit">
      <div>
        <label for="email">Email:</label>
        <input type="email" id="email" v-model="form.email" @input="validateEmail" />
        <span v-if="errors.email">{{ errors.email }}</span>
      </div>

      <div>
        <label for="password">Password:</label>
        <input type="password" id="password" v-model="form.password" @input="validatePassword" />
        <span v-if="errors.password">{{ errors.password }}</span>
      </div>

      <button type="submit" :disabled="!isFormValid">Submit</button>
    </form>
  </div>
</template>
Vue 3 template code defining a form with two input fields for email and password with dynamic validation and reactive error messages.
<script setup>
import { ref, computed } from 'vue';

const form = ref({ email: '', password: '' });
const errors = ref({ email: null, password: null });

function validateEmail() {
  const emailRegex = /\S+@\S+\.\S+/;
  errors.value.email = emailRegex.test(form.value.email) ? null : 'Invalid email address';
}

function validatePassword() {
  const minPasswordLength = 6;
  errors.value.password = form.value.password.length >= minPasswordLength ? null : 'Password must be at least 6 characters long';
}

const isFormValid = computed(() => {
  return Object.values(errors.value).every(error => error === null);
});

function handleSubmit() {
  console.log('Form submitted with:', form.value);
}
</script>
Vue 3 Composition API script that defines state for the form and errors, validation functions for email and password, and computed state for form validity.
<style>
input {
  margin-bottom: 10px;
  border: 1px solid #ccc;
  padding: 8px;
}

span {
  color: red;
  font-size: 14px;
}

button:disabled {
  opacity: 0.5;
}
</style>
CSS styles to style the input fields, display error messages in red and tweak the appearance of the disabled submit button.