Unique Email Validation in Vue with Vuelidate and Firebase REST API

In your html code add:

<input type="email" id="email"
 debounce="300" v-model="email"></input>
<div v-if="$v.email.unique && !$v.email.$pending" class="input-warning">Email Already Taken</div>

In your Vue JavaScript code add:

...
validations: {
    email: {
      async unique (val) {
        if (val.trim().length === 0) return true
        let isUnique = true
        const emailRegex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

        if (emailRegex.test(val)) {
          console.log('is a valid email, checking if unique')

          const response = await axios.post(':createAuthUri?key=xyz_abc_123', {
            identifier: val,
            continueUri: window.location.href
          })
            .catch((ex) => {
              console.log('error:', ex)
              return true
            })

          console.log('response:', response)
          isUnique = !response.data.registered
        }
        return await Boolean(isUnique)
      }
    }
  },
...

Couple of important things to note

  1. I’m not using semi-colons at the end of my lines – up to you whether you wish to or not
  2. Regex – This I think is a key element that I don’t see used very often elsewhere – you see we don’t want to check if email is unique after every single key press – we are as well to wait until they enter in a valid email first – then start checking. This reduces down the amount of calls being made to Firebase
  3. Using $pending – for whatever reason, while the async process is off doing its thing the value of ‘unique’ gets set to ‘false’ for that split second before the async process is complete – once its complete it gets set to whatever is returned by the async call. So what was happening was the error message was appearing on the screen after every key press for a split second before disappearing. I noticed that the $pending value was also getting set to true during that split second. So by combining both in your ‘if’ statement you can prevent this error message from incorrectly popping up.

And that’s pretty much it!