CodexBloom - Programming Q&A Platform

Vue 3 Form Validation with VeeValidate: Async Validation optimization guide as Expected

πŸ‘€ Views: 58 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-08
vue.js vee-validate validation async javascript

This might be a silly question, but I'm currently working on a form in Vue 3 using VeeValidate for validation, and I'm working with an scenario with async validation not triggering correctly on input change... I have a username field that needs to check against an API to see if the username is already taken. I set up the validation rules but the async function is not being called when I change the input. Here’s what I have so far: ```javascript import { defineRule, validate } from 'vee-validate'; import { required, alpha } from '@vee-validate/rules'; import { ref } from 'vue'; defineRule('required', required); defineRule('alpha', alpha); defineRule('username', async (value) => { const response = await fetch(`https://api.example.com/check-username?username=${value}`); const data = await response.json(); return data.available ? true : 'Username is already taken.'; }); const username = ref(''); const errors = ref({}); const validateUsername = async () => { errors.value.username = await validate(username.value, 'required|username'); }; return { username, errors, validateUsername }; ``` In my template, I have: ```html <input v-model="username" @input="validateUsername" /> <span v-if="errors.username">{{ errors.username }}</span> ``` The question is that when I enter a username, the behavior message does not update to reflect the async validation result. I'm not seeing any API calls being made in the network tab when I type in the input field, and it seems like the async rule is not being triggered. I've verified that the API URL is correct and returns expected data. I also tried using the `validate` function directly on the username input instead of calling it from the method but it still doesn't seem to work. Any suggestions on what might be going wrong here? I'm using VeeValidate 4.5.0 and Vue 3.2.0. For context: I'm using Javascript on Ubuntu. How would you solve this?