How to implement debouncing for an asynchronous custom validator in Vue.js using vuelidate?

I encountered an issue with my validator function that checks if a username is already registered in the database. The problem was that the request was being sent to the server after every single character input, which was far too frequent. To remedy this, I attempted to debounce the process of setting the username variable value. However, I kept running into this error:

Uncaught TypeError: Cannot read property 'value' of undefined 
at a.NHnr.q.methods.debounceUsername.H.a.debounce.leading

Vue script:

import uniqueUsername from '../validation/uniqueUsername'
import _ from 'lodash'

export default {
    name: "signUpPage",
    data() {
      return {
        credentials: {
          username: ''
        }
      }
    },
    methods: {
      debounceUsername:
        _.debounce(function (e) {
          this.credentials.username = e.target.value;
        }, 200, {leading: false, trailing: true})
    },
    validations: {
      credentials: {
        username: {
          uniqueUsername: uniqueUsername
        }
      }
   }
}

Html:

    <b-field :label="msg('usernameLabel')"
             :class="{ 'form-group--error': $v.credentials.username.$error }">
      <b-input size="is-large" type="text" class="form__input"
               icon="account" name="username" v-on:input="debounceUsername" autofocus="">
      </b-input>
    </b-field> 
//b-field and b-input are from buefy library

Custom validator (uniqueUsername.js):

import axios from 'axios'

export default value => {
  if (value.trim().length === 0) return true;
  let usernameUnique;
  return new Promise(async function (resolve) {
    await axios('/isUsernameUnique', {
      method: "post",
      data: value,
      headers: {'Content-type': 'text/plain'}
    }).then((response) => usernameUnique = response.data);
    if (usernameUnique) resolve('username is unique');
  });
};

Answer №1

To ensure proper validation, one method is to trigger async validations when the user moves out of an input field (on blur event). Here's how you can implement it:

<input @blur="$v.username.$touch" v-model.lazy="username" />

Below is a sample script illustrating this approach:

export default {
  data () {
   return {
    username: ''
   }
  },
  validations: {
    username: {
     required,
     isUnique(username) {
       if (username === '') return true
       return axios.get('/checkUsername')
                 .then(res => {
                   return res.data //res.data should evaluate to true or false based on DB check for existing username
                 }) 
     }
    }
  }
}

Please note: For this code to function properly, make sure to import axios and required from vuelidate.

Additionally, remember that the backend must respond with false if the username is indeed unique for the above code to operate correctly.

Answer №2

After some troubleshooting, I finally discovered the solution. I needed to modify

this.credentials.username = e.target.value;

to:

this.credentials.username = e;

Success! The issue has been resolved and now requests are only sent once every 200ms.

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

Navigate through the overlay's content by scrolling

Objective: Looking to implement a scroll feature for long content. Issue: Not sure how to create a scroll that allows users to navigate through lengthy content. Thank you! function openNav() { document.getElementById("myNav").style.height = "1 ...

AngularJS - ng-repeat: Warning: Repeated items found in the repeater and are not allowed. Repeater:

I'm currently using ng-repeat to showcase a collection of items fetched from the Twitter API. However, I am encountering an issue where Angular attempts to display the empty list while the request is still being processed, resulting in the following e ...

Using PHP to track the number of clicks on a specific div element

Although I am not well-versed in javascript, I have incorporated it into my website to enhance its appearance. One of the features I've added is a popup that appears when a user clicks on a specific div element to display additional information. In ad ...

Bring in all SCSS styles from a single file and apply them to a React component

I am attempting to incorporate the entire SCSS file into a React component. I attempted to use the styleName props but was unsuccessful import React from 'react' import Calendar from 'calendar' import { calendarStyles } from './ ...

Using Selenium to interact with a link's href attribute through JavaScript

New to Java and Selenium, I'm facing difficulties when trying to click on a link with JavaScript in href attribute. Here's the snippet from the page source: href="javascript:navigateToDiffTab('https://site_url/medications','Are y ...

"Ensuring Contact Information is Unique: A Guide to Checking for Existing Email or Phone Numbers in

I'm encountering an issue with validating email and phone numbers in my MongoDB database. Currently, my code only checks for the presence of the email but does not respond to the phone number. const express = require("express"); const router ...

Develop and arrange badge components using Material UI

I'm new to material ui and I want to design colored rounded squares with a letter inside placed on a card component, similar to the image below. https://i.stack.imgur.com/fmdi4.png As shown in the example, the colored square with "A" acts as a badge ...

What is the best method for deleting an uploaded image from a box?

My code is quite lengthy, so I'll just showcase the JavaScript portion here. Here is a snippet of my JavaScript code: <script type="text/javascript"> let current = 0; for(let i = 0; i < 5; i++) { $('#thumbnail-view- ...

Looking for assistance in showcasing information retrieved from an external API

I've been working with an API and managed to fetch some data successfully. However, I'm having trouble displaying the data properly in my project. Can anyone provide assistance? Below is a screenshot of the fetched data from the console along wit ...

steps for linking a directive variable to a controller

Encountering an issue with 2-way binding in Angular where changes made to the input do not reflect in the controller. However, the initial value set by the controller does affect the directive. In the screenshot, a value was changed but vm.date still hold ...

Using Node.js to efficiently parse JSON data into customizable PUG templates

I have a challenge where I am parsing JSON data into elements called homeCards. To achieve this, I use Axios to request the JSON data and then utilize a for loop to cycle through it. Inside my Axios function, I extract the fields I need and store them in v ...

Set up a single array containing multiple objects in a table, each with its own unique set of keys

I am currently developing an application that retrieves data from one or multiple databases, each with different names and varying numbers of columns. The goal is to consolidate this data into a single report screen and export it as a table. While the tabl ...

Updating parent scope from modal component in Vue2

I am currently working on a modal component that takes input, creates a record on the backend, and upon successful response, I want to update an object in the parent scope with the received data. Although I have attempted to emit an event from the child c ...

Vue.js Google Places Autocomplete Plugin

I'm currently working on integrating Google Places Autocomplete with Vue.js. According to the API documentation, the Autocomplete class requires an inputField:HTMLInputElement as its first parameter, like shown in their example: autocomplete = new g ...

Is it possible in MongoDB to embed a collection within a document of another collection?

Working with Javascript, Node.js, Express, and MongoDB for a web application. Users can create an account with fields for name and last name, but I also need to track completed steps using a boolean value (false for uncompleted, true for completed). Instea ...

Combine an array of arrays with its elements reversed within the same array

I am working with an array of numbers that is structured like this: const arrayOfArrays: number[][] = [[1, 2], [1, 3]]; The desired outcome is to have [[1, 2], [2, 1], [1, 3], [3, 1]]. I found a solution using the following approach: // initialize an e ...

When trying to install express using Node.js npm, an error message 'CERT_UNTRUSTED' is preventing the installation of express

My goal is to set up express on Raspberry Pi for the purpose of using it in a REST API. However, I keep encountering an issue with SSL certification when trying to install it through npm. Despite attempting various solutions found on different forums, I ha ...

Encountering a missing value within an array

Within my default JSON file, I have the following structure: { "_name":"__tableframe__top", "_use-attribute-sets":"common.border__top", "__prefix":"xsl" } My goal is to add values by creating an array, but I am encountering an issue where my ...

What are the steps for creating an animated visualization of the peak chart?

As a newcomer to CSS and Javascript, I am currently struggling with animating a peak (bar) chart that I came across on codepen. If anyone can provide assistance or guidance, it would be greatly appreciated! The chart can be found here: http://codepen.io/An ...

Specify a non-string value (such as primitives, object, or expression) for checkbox true-value and false-value

I am experiencing difficulty in changing the v-model value to anything other than a string when the checkbox is checked or unchecked. https://jsbin.com/haqofus/edit?html,console,output <div id="app"> <div><input type="checkbox" v-model ...