0

I'm trying to add a custom async validation to a form in Vue and following the documented example, but the validation never fails. Here is my code:

<script>
import { reactive } from 'vue';
import useVuelidate from '@vuelidate/core';
import { required, email } from '@vuelidate/validators';

export default {
  template:
    '<input v-model="state.postcode" /><div v-if="v$.postcode.$silentErrors.length">never shows</div>',

  setup() {
    const state = reactive({
      postcode: 'OX14 8JW',
    });

    const rules = {
      postcode: {
        async startsWithX(value) {
          await new Promise((resolve) => setTimeout(resolve, 1000));
          const isOk = value && value[0] === 'X';
          //   console.log('sanity check: ', isOk);
          return Boolean(isOk);
        },
      },
    };

    const v$ = useVuelidate(rules, state);

    return { v$, state };
  },
};
</script>

Can someone help me to get this async validation working?

tony19
  • 125,647
  • 18
  • 229
  • 307
Jannie Theunissen
  • 28,256
  • 21
  • 100
  • 127

1 Answers1

1

The example link you posted has not been updated to the latest changes (notice the sidebar heading is "Examples (outdated)").

The current docs for Async validators state:

Async validators that return a Promise, need to be wrapped in the withAsync helper. This will tell Vuelidate to treat the validator in a special way, tracking pending status, storing response and more:

//...
import { helpers } from '@vuelidate/validators'

const { withAsync } = helpers

export default {
  setup() {
    const state = reactive({
      postcode: 'OX14 8JW'
    })

    const rules = {
      postcode: {       
        startsWithX: withAsync(async (value) => {
          await new Promise((resolve) => setTimeout(resolve, 1000))
          const isOk = value && value[0] === 'X'
          return Boolean(isOk)
        })
      }
    }

    const v$ = useVuelidate(rules, state)

    return { v$, state }
  }
}

demo

tony19
  • 125,647
  • 18
  • 229
  • 307