Reputation: 15
I'm currently making my first web app (CRUD) using Vue 2 + Vuetify, but I've encountered a problem with a feature I wanna add into a form, which is validation to ensure that there's no item with the same title in the database already.
Here is the code sample using a fake API. Below is the block of code if you prefer it (using the real API).
The HTML part:
<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 returns no data if no same title are found, or exactly 1 record if the same title exists. It works if I put the checking part outside the axios.then (in code sample, uncomment the part and run it if you wanna try); it is compared to "test" and does validate correctly. But when it's only inside the .then block, it doesn't work at all! (both using the "test" and the response.data.title)
I tried to store the response in a variable outside the axios.then to compare it outside, but from what I've read (and tried too), it's not possible because it's async (I still don't really understand it?). I've tried async-await, and all sorts of stuff in Stack Overflow, but none has solved this issue.
Is there any way to solve this problem? As long as the feature are implemented, I don't mind changing my method.
Sorry if the code are a mess, I followed a tutorial and just played around with it. Let me know if you need more info, thanks for the help!
Upvotes: 0
Views: 2068
Reputation: 528
Sorry, I don't have the reputation to comment so answering, basically you are trying to implement asynchronous rule in vuetify text field which vuetify doesn't support directly, there are few workarounds that you can check out here. How to make a Vuetify rule async and await with a ajax call
This is an open issue in github: https://github.com/vuetifyjs/vuetify/issues/4231
Few more workaround references: How to validate Vuetify text field asynchronously? Let me know if it solves your issue.
Upvotes: 2