0

I want to check the availability of a username in a database querying to an API. The code related to the rule that evaluate the field is:

extend('exists', value => {
     apiService.checkUsername(value)
        .then(response => {
            response.data[0].username == value?true:false;
    })
        .catch(response => alert(response.message));
}, {
    immediate: false
}) 

My problem is: the error message is shown before the API's response. I wanna show it after the response. Any idea?

VicentGN
  • 23
  • 5
  • what error message? – T. Short Jan 09 '20 at 20:01
  • For example: 'The username exists' – VicentGN Jan 09 '20 at 20:55
  • Are you talking about `.catch(response => alert(response.message));`? Sorry, I'm having trouble understanding your question. – T. Short Jan 09 '20 at 21:05
  • No. I mean: Imagine that you're trying to register on a website using a form which contains a field that evaluates if a username exists or not (the field calls an API and the API sends a response (a JSON object) with information about the username and other data you have requested (in case of the username exists on the DB). If the system receives that object, the form will show you a message saying: 'The username is not available. Try another one'. My question is related on how and when that message will be shown inside of a registration process. Sorry, but I'm a newby using this technology. – VicentGN Jan 09 '20 at 21:17
  • It would happen inside the `.then() ` part. You check for the value of the response and proceed accordingly... – T. Short Jan 09 '20 at 21:20
  • Ok. But, how can I manage an empty response? I wanted to use a condition which returns true if the response is not empty and false if it's empty (for example if the username doesn't exist...) – VicentGN Jan 09 '20 at 21:24
  • What kind of value does it return? An array, string, boolean... Show us an example of what is inside the response – T. Short Jan 09 '20 at 21:26
  • `extend('exists', value => { apiService.checkUsername(value) .then(response => { response.data.length == 1?true:false; }) .catch(response => alert(response.message)); })` – VicentGN Jan 09 '20 at 21:31
  • What is the value of `response.data` – T. Short Jan 09 '20 at 21:32
  • [object Object] – VicentGN Jan 09 '20 at 21:41

1 Answers1

0

Return the promise from your validate function - then vee-validate will wait until it completes before doing anything further. I couldn't find any reference for this, but I think it should work.

extend('exists', value => {
     return apiService.checkUsername(value)
        .then(response =>
            response.data[0].username == value?true:false;
        )
        .catch(response => alert(response.message));
})
Ryley
  • 21,046
  • 2
  • 67
  • 81