Guide on developing a personalized validation system with Vuetify regulations for verifying the presence of an item

I'm currently working on my first CRUD web app using Vue 2 + Vuetify, but I've hit a roadblock while trying to add validation to a form. Specifically, I need to ensure that no item with the same title already exists in the database.

You can view the code sample with a fake API, or see below for the code snippet using the real API.

Here is the HTML portion:

<v-form ref="form" lazy-validation> 
  <v-text-field
    v-model="editedItem.title"
    :rules="[rules.required, checkDuplicate]"
    label="Title"
  ></v-text-field>
</v-form>

The Method part:

data() {
  return {
    editedItem: {
      title: '',
    },
    rules: {
      required: value => !!value || 'Required.',
    },
  }
},
methods: {
  checkDuplicate(val){
    let params = {};
    params["title"] = val;

    if (val){ //If null, don't call the API
      InventoryDataService.findExactTitle(params)
      .then((response) => {
        if(response.data != ""){ // Same title are found
          if (val == response.data.title) { // Can be discarded, but just to make it same as code sample
            return `Inventory titled ${val} already exists`;
          }
        }
        else{ // No same title found
          return true;
        }
      })
      .catch((e) => {
        console.log(e);
      });
    }
    else{ // Text field is empty
      return true;
    }
  },
}

The actual API will return either no data if there isn't a duplicate title, or exactly one record if the same title already exists. The logic works when checking outside of the axios.then block (uncomment this part in the code sample to test it), comparing to "test" and validating correctly. However, when this comparison is within the .then block, it doesn't work at all! (both using "test" and response.data.title)

I have attempted to store the response in a variable outside of axios.then for external comparison, but due to the asynchronous nature, it seems impossible (I still struggle to understand this concept?). I've experimented with async-await and consulted various resources on Stack Overflow, yet none have resolved the issue.

Is there any workaround to address this challenge? I am open to modifying my approach as long as the desired feature is achieved. Apologies if the code appears messy, as I followed a tutorial and made adjustments along the way. Please let me know if you require additional information. Thank you for your assistance!

Answer №1

Apologies, I lack the reputation to comment but I can provide an answer instead. It seems like you are attempting to implement an asynchronous rule in a Vuetify text field, which is not directly supported by Vuetify. However, there are some workarounds that may be helpful. You can find more information here.

This issue has been raised on Github as well: https://github.com/vuetifyjs/vuetify/issues/4231

For additional workaround references, you can check out this link: How to validate Vuetify text field asynchronously?. Feel free to let me know if this helps resolve your problem.

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

An error occurred while defining props due to a parsing issue with the prop type. The unexpected token was encountered. Perhaps you meant to use `{`}` or `}`?

const dataProps = defineProps({ selectedData: <Record<string, string>> }); Under the closing bracket, there is a red line indicating: Error: Unexpected token. Consider using {'}'} or &rbrace; instead?eslint Expression expecte ...

Creating responsive tables in ag-grid-vue with VueJS to adjust column widths and fit the table to any screen size

I am currently utilizing Ag-grid to present a table, and my goal is to ensure that the table is responsive. My aim is to have the entire table or columns adjust their width according to the screen size: If the screen width is below 500px, then I want the ...

Unable to retrieve ajax responseText within a jquery function

Seeking assistance with a form designed for user registration. Utilizing jQuery and AJAX to validate email address availability upon blur event. Employing e.preventDefault(); in JQuery code to prevent form submission in case of errors. However, encounterin ...

How to Send a JavaScript Array to a JSP Endpoint

I'm in the process of creating a web application that interacts with another website through a JS API. I would like to incorporate an array of JSON objects obtained from this API into my Java Application. Is there any way to submit this array, perhap ...

Developing a realtime search feature using AJAX and CodeIgniter

Attempting to implement a live search feature in CodeIgniter for the first time. As a newcomer to web development, still in the learning process. Came across a tutorial on how to achieve this here. Struggling with adapting the code from the tutorial to fi ...

A dedicated folder for hosting the static assets generated by Nuxt.js

I have a quick question I'm looking to create a dedicated directory for the static files generated by Nuxt Js Currently, Nuxt Js compiles all files into a single directory called 'dist' As I am utilizing Django Server as my backend, I nee ...

Setting up Spectron

I attempted to install Spectron using the following command: npm install --save-dev spectron However, I encountered the following error message: npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\P ...

When implementing auto-generated IDs in HTML forms, rely on randomly generated values for increased uniqueness

When developing a form with multiple complex controls built as Backbone views, one wants to ensure that the labels are correctly linked to the input elements. This is typically done using the "for" attribute. However, in cases where the same control needs ...

Accessing table cell value when clicked using JavaScript or jQuery

I am currently working on an ASP.NET MVC application where I have a table displaying records from the database in razor code. My goal is to extract the record ID "FeeZoneID" from a cell value when the delete link in the last column is clicked, and then t ...

Retrieving all the information stored in the tables

I'm struggling with retrieving the content of my table cells. Some cells contain a hyphen (-) and if they do, I want to center the text. I'm facing difficulties with my jQuery code, particularly the if statement which always evaluates to false. ...

Issue with React Google Maps Api: Error occurs while trying to access undefined properties for reading 'emit'

I'm trying to integrate a map using the google-map-react API, but I keep encountering the following error: google_map.js:428 Uncaught TypeError: Cannot read properties of undefined (reading 'emit') at o.r.componentDidUpdate (google_map.js: ...

Track the number of views each month using PHP and MySQL to generate dynamic jQuery charts

I am currently utilizing jQuery with chart.js to display the view counter based on month using PHP and MySql. Each page view is inserted into MySql in the following format : | id | ip | page | date(timestamp) | | 1 | 138.86.20.20 | test.p ...

Am I causing my entire React component to re-render needlessly every time the state changes?

I've been attempting to develop an accordion component using React, but I seem to be encountering issues with the animation not functioning as expected. The approach I'm taking is quite standard - setting a max-height of 0 for each item body and ...

Differentiate input elements with custom styling

I'm experiencing an issue while trying to style a specific form field in Angular 7. The style doesn't seem to be applying properly. Below is my form structure: <ul> <li> <mat-form-field *ngIf="number"> <input ma ...

Accept only numerical input, any other type will prompt a notification

Ensuring that users can only input numbers is functioning properly. If a user attempts to enter anything other than a number, an error message should be displayed. I have experimented with Validators and patterns, but I am unable to get the error message ...

Ways to Retrieve the Text From the Selected Index in Datalist Element

I need to extract the inner text of the option tag using pure JavaScript This is the HTML code I am working with: <input list="in" name="i_n" class="form-control" placeholder="Enter Item Name" required> <datalist id="in" onChange="rate(this)"&g ...

How to eliminate duplicate items in an array and organize them in JavaScript

I am looking to eliminate any duplicate items within an array and organize them based on their frequency of occurrence, from most to least. ["57358e5dbd2f8b960aecfa8c", "573163a52abda310151e5791", "573163a52abda310151e5791", "573163a52abda310151e5791", "5 ...

Conceal certain components when a user is authenticated

Below is the content of my app.component.html: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class='container'> <ul class="nav navbar-nav"> <li class='nav-item'> <a clas ...

Trouble Arising from Making a POST Request to Spotify's API

I am currently developing a web application that allows users to search the Spotify Library, add songs to playlists, and then save those playlists to their Spotify Accounts. Almost everything is functioning correctly except for the saving of playlists thro ...

Guide on executing a function exclusively when the state of a service variable changes within an Angular4 component

In my InfoFormService, I have a variable called isInValidating that is initially set to false. This variable becomes true when the component calls the validateEmail(email) function as shown below. @Injectable() export class InfoFormService { private ...