I aim to show an error notification if a duplicate email address is detected in a Vuetify form

The Presumption

While working on a user registration form with Vuetify, I encountered a challenge. How can I set up an error message to display if the user tries to register with an email address that already exists? My aim is to utilize Vuetify's textfield for this functionality. The email component is already configured within the form, using v-model to ensure reactive updates.

Our Objective

I intend to use v-text-field from Vuetify to exhibit an error when an existing email address is used during registration.

The Code Implementation

Email Section

UserFormTextFieldEmail

<template>
  <v-row justify="center">
    <v-col cols="12" md="10" sm="10">
      <v-text-field
        v-model="setEmail"
        type="text"
        label="email"
        prepend-icon="mdi-email"
        :rules="rules"
      />
      <p class="caption mb-0" />
    </v-col>
  </v-row>
</template>
<script>
export default {
  props: ['email'],

  data () {
    return {
      rules: [
        v => !!v || '',
        v => /.+@.+\..+/.test(v) || ''
      ]
    }
  },

  computed: {
    setEmail: {
      get () { return this.email },
      set (newVal) { return this.$emit('update:email', newVal) }
    }
  }
}
</script>

Form Section

  <v-card class="pa-7 ma-10 mx-auto" max-width="600">
      <div class="login-logo">
        <img
          :src="logoImg"
          width="70px"
        >
      </div>
      <v-form
        ref="form"
        v-model="isValid"
      >
        <v-container>
          <UserFormTextFieldUserName :name.sync="userInfo.name" />
          <UserFormTextFieldEmail :email.sync="userInfo.email" :error.sync="errorMessage" /> // email
          <UserFormTextFieldPassword :password.sync="userInfo.password" />
          <v-row justify="center">
            <v-col cols="12" md="10" sm="10">
              <v-btn
                :disabled="!isValid || loading"
                :loading="loading"
                block
                class="white--text"
                color="deep-purple lighten-1"
                @click="signup"
              >
                ・・・
              </v-btn>
            </v-col>
          </v-row>
        </v-container>
      </v-form>
    </v-card>
  </div>
</template>

<script>
import '@/assets/css/user-form.scss'
import logoImg from '~/assets/images/login_logo.png'
export default {
  auth: false,
  data () {
    return {
      isValid: false,
      loading: false,
      logoImg,
      show: false,
      userInfo: {
        name: '',
        email: '',
        password: ''
      },
      errorMessage:''
    }
  },
  methods: {
    signup () {
      this.$axios.post('/api/v1/auth', this.userInfo)
      .then((response) => {
        this.$store.commit('alertSwitchSuccess', true)
        setTimeout(() => {
          this.$store.commit('alertSwitchSuccess', false)
          this.$router.replace(`/user/login`)
        }, 2000)
      })
      .catch((e) => {
      })
    }
  }
}
</script>

Answer №1

In the past, I encountered a similar issue and here's how I resolved it:

methods: {
    validateEmail() {
      axios
        .get("/api/v1/auth")
        .then((response) => {
          this.emails = response.data.map((item) => 
          item.email);
        });
    },
},

This method will fetch an array of all emails.

data() {
    return {
      //email input v-model
      email: "",
      //initialize the emails array
      emails: [],
      rules: [
        // your validation rules
        (value) =>
          (value && this.emails.indexOf(this.email)<0)||
          "this email already exists",
      ],

I trust this solution will be beneficial to you

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Maintaining binding while appending inner elements within a container using jQuery

I'm struggling to transfer the contents of one container to another without losing any bindings, and it's proving quite tricky! <div class="container"> <div class="field"> <label>Username</label> < ...

Create a new variable to activate a function within the parent component in Vue

I want to invoke a function in the parent component from its child component. In my Vue project, I have designed a reusable component that can be used across multiple pages. After the function is executed in this component, I aim to call a specific functi ...

Troubleshooting IE Resolution Problem with getElementsByClassName

I am struggling with how to fix the getElementsByClassName issue in IE. What is the best way to incorporate the Robert Nyman solution into my code without being able to post the link? Or should I consider using a jQuery solution instead? Here's the co ...

What is the process for customizing the heading titles on various pages within the Next.js application directory?

Within the app directory of Next.js 13, I have a default root layout setup: import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <head> <title>Create ...

Why is Ajax/FormData rounding my decimal values?

When sending data from a form to my PHP script, I am utilizing the new FormData() method to retrieve the values. However, there are additional values that I append later on which are not part of the form: var fd = new FormData(document.getElementById(&apo ...

The error message "Vue.JS computed from VueX Store is not recognized" is displaying

Within my Vuex store, I am able to see it in the Vue Devtools tool. However, when attempting to load data into a computed property, an error message stating that it is not defined is displayed. computed: { userData(){ return this.$store.state.use ...

Implementing a queue within each iteration in JavaScript

How can synchronization be achieved in a JavaScript loop? Here is an example without synchronization : $.each(data, function(index, value) { alert(index + ': ' + value); }); Attempt at synchronization : var time = 500; $.each(data, functi ...

Validation of time picker consistently returns false

While using the daterangepicker library for my form validation with JavaScript, I encountered an issue with the time field. It returns false and displays an error message saying: "Please enter a valid time, between 00:00 and 23:59," preventing me from addi ...

Select value not updating as expected

I have a select box that is linked to a switch statement in PHP, which changes the order of the results returned from the database based on the value selected in the select box. However, I am facing an issue with my JavaScript not working correctly. Can an ...

How can the LinkedIn insights code be integrated into Vue to ensure proper triggering?

What is the best method for implementing LinkedIn insights code in a Vue project to ensure it triggers properly? Is adding the code before the closing body tag sufficient? ...

When you click, activate a trigger called component and control clicking outside of the element

I am in the process of creating a custom Vue component called Dropdown.vue. It features a prop named name, allowing me to activate it by clicking on any specified div element. For instance, I have an element defined as <button @click="openDropdown ...

Ember.js Helper that mimics an Ajax request response

After extensive exploration and experimentation, it seems that returning a value from an ajax request in Emberjs is quite challenging. (I could be mistaken.) The issue appears to be related to the asynchronous nature of callbacks. Here lies my predicament ...

Issue with the select tag not responding to @change event in Vue3 composition API

I attempted using @change and watch with no success. How can I detect when the select value is changed? This is the code snippet I am working with: <select v-model="selected" @change="changeLang()" > <option v-for="i ...

ionRangeSlider adjusts values according to a given percentage

I am currently utilizing the ionRangeSlider library for my project. My goal is to synchronize 2 sliders based on their current percentage. Below is the code I have implemented: $(function(){ $("#foo").ionRangeSlider({ type: "single", grid: t ...

Do I need to utilize getStaticProps along with JSON imports in Next.js?

Is it necessary to use getStaticProps in order to render static data from a JSON or typescript file, or can the data be imported without using getStaticProps? The documentation I read didn't provide a clear answer. projects.tsx const projects: [ { ...

Routing in Node.js does not navigate to every internal route within an Angular application

I am currently developing a frontend application using Angular 9. In order to run the application, I have set up a NodeJs server to handle all incoming requests and direct them to the Angular Dist (Build) files. Issue at Hand The main problem I am facing ...

What is the secret behind Redactor JS's ability to display properly indented code snippets?

If you take a look at the Redactor JS demo and click on the button to show the HTML source code of the displayed content... ...you will notice that the code is properly indented: Most rich text editors or wysiwyg editors typically display code in a singl ...

JavaScript Naval Combat Game

I created a basic battleship game using javascript, but unfortunately it's not working properly. I stored the ship locations in an array and attempted to remove guessed locations by using the splice method. However, it keeps displaying "MISS!" when nu ...

Click on all elements within a specified division

I'm encountering an issue with selecting all the content within a specific div element. Here's a demonstration of the problem: http://jsfiddle.net/KcX6A/304/ Currently, only the first line of text is being selected, while the rest is being igno ...

What is the method for retrieving a value using the Angular forEach function?

I'm encountering an issue with retrieving values from an angular forEach loop. Below is the data I am working with: vm.memberDetails={ "member": [ { "firstName": "HARRY UTTWO", "lastName": "POTTER", } ...