form validation example in vue version 3 composition api in javascript

Here is an example of form validation using Vue 3 Composition API in JavaScript:

<template>
  <form @submit.prevent="submitForm">
    <div>
      <label for="name">Name:</label>
      <input type="text" id="name" v-model="name" :class="{ 'is-invalid': !nameIsValid }">
      <div v-if="!nameIsValid" class="invalid-feedback">Please enter a valid name</div>
    </div>
    <div>
      <label for="email">Email:</label>
      <input type="email" id="email" v-model="email" :class="{ 'is-invalid': !emailIsValid }">
      <div v-if="!emailIsValid" class="invalid-feedback">Please enter a valid email address</div>
    </div>
    <button type="submit">Submit form</button>
  </form>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const name = ref('');
    const email = ref('');
    const nameIsValid = ref(true); // We assume the name is valid by default
    const emailIsValid = ref(true); // We assume the email is valid by default

    // Form validation logic
    function validateForm() {
      nameIsValid.value = name.value.length > 0;
      emailIsValid.value = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.value);
    }

    // Form submit handler
    function submitForm() {
      validateForm();

      if (!nameIsValid.value || !emailIsValid.value) {
        return; // Do not proceed if the form is not valid
      }

      // Form is valid, do something here
    }

    return { name, email, nameIsValid, emailIsValid, submitForm };
  }
};
</script>

<style>
.is-invalid {
  border-color: red;
}
.invalid-feedback {
  color: red;
  font-size: 0.8em;
  margin-top: 5px;
}
</style>
1541 chars
59 lines

In this example, we use the ref function from Vue 3 Composition API to create reactive variables for name, email, nameIsValid, and emailIsValid. We then define a validateForm function that updates the nameIsValid and emailIsValid variables based on their values. Finally, we define a submitForm function that calls validateForm and does not allow the form to be submitted if it is invalid.

gistlibby LogSnag