Vue 3 Reactive Form with Composition API

Build reactive forms in Vue 3 using the Composition API with ref and computed. Includes two-way binding, validation rules, dynamic field generation, and.

Javascript Vue Form Validation

Code

snippet
import { ref, computed } from 'vue';

export function useForm(initialValues) {
  const values = ref({ ...initialValues });
  const errors = ref({});
  const loading = ref(false);

  const validate = (rules) => {
    errors.value = {};
    for (const [field, rule] of Object.entries(rules)) {
      if (rule.required && !values.value[field]) {
        errors.value[field] = rule.message;
      }
    }
    return Object.keys(errors.value).length === 0;
  };

  const submit = async (onSubmit) => {
    loading.value = true;
    try { await onSubmit(values.value); }
    finally { loading.value = false; }
  };

  return { values, errors, loading, validate, submit };
}