Asynchronous Validators on the Next branch
See original GitHub issueGood time of the day.
I’ve decided to play around with the next
branch (or @vuelidate/core
and @vuelidate/validators
) and i’ve faced an issue i cannot wrap my head around.
Right now, on the stable
branch i am using the following validator to perform async validations:
export function asynchronousValidator (validator: Function, delay: number = 2000) {
let currentTimer: NodeJS.Timeout|null = null;
let currentPromiseReject: any = null;
const debounce = () : Promise<void> => new Promise((resolve, reject) => {
currentTimer = setTimeout(() => {
currentTimer = null;
currentPromiseReject = null;
resolve();
}, delay);
currentPromiseReject = reject;
});
return (value: any) => {
if (currentTimer) {
currentPromiseReject(new Error('Replaced'));
clearTimeout(currentTimer);
currentTimer = null;
}
// @ts-ignore
return validator.call(this, value, debounce);
}
}
and i have this validation in place:
username: {
required,
minLength: minLength(8),
maxLength: maxLength(32),
isUnique: asynchronousValidator(function (value: string, debounce: Function) {
if (isUndefinedOrNull(value) || value === '') {
return true;
}
return debounce()
.then(() => PeopleService.usernameExists(value))
.then((exists: boolean) => !exists)
.catch(() => false);
}, 1200)
}
However, on the next
branch, there is a new way of creating asynchronous validators
.
By going through the source code, i found that you can do the following common.withAsync((value: string) => {});
However, for some reason, there is no way in adapting the code i have (for input debouncing). Either it is not working at all, it gets called (by using the console.log
i can see that each part of it is working), but there is no output (validation not happens).
Or, it constantly throwing errors about not being able to access the .then
method as it does not exists.
I’ve tried this
export function asynchronousValidator (validator: Function, delay: number = 2000) {
let currentTimer: NodeJS.Timeout|null = null;
let currentPromiseReject: any = null;
const debounce = () : Promise<void> => new Promise((resolve, reject) => {
currentTimer = setTimeout(() => {
currentTimer = null;
currentPromiseReject = null;
resolve();
}, delay);
currentPromiseReject = reject;
});
return withAsync((value: any) => {
if (currentTimer) {
currentPromiseReject(new Error('Replaced'));
clearTimeout(currentTimer);
currentTimer = null;
}
// @ts-ignore
return validator.call(this, value, debounce);
});
}
But as i said, no result is returned, or this error is thrown (yes, can be both, no idea why).
I am using latest Vue 2
with latest composition-api
on latest nuxtjs
Issue Analytics
- State:
- Created 3 years ago
- Comments:15 (5 by maintainers)
Ran into this same issue and looked at your code sandbox (https://codesandbox.io/s/vuelidate-async-validator-forked-uxtgm), but changed the promise to resolve true (rather than false) and the field still shows as invalid?