Async validators called twice, first for fails and then again for passes callback
See original GitHub issueWhen there are only sync validators I can check if it passes or fails using only either a call to validation.fails()
or validation.passes()
like so:
let validation = new Validator(data,rules);
if (validation.passes()) {
//handle passed validation
} else {
//handle failed validation
}
In this scenario the validation test runs only once, when calling to fails()
.
The problem arises when Async Validators are present. It needs to be a callback
when calling fails
or passes
functions but in order I can cover both fail and pass scenarios I’d need to call both functions, like so:
let validation = new Validator(data,rulesWithAsyncValidators);
validation.passes(()=>{
//handle passed validation
});
validation.fails(()=>{
//handle failed validation
});
In this async scenario the validation test runs twice, first when calling passes
and then again when calling fails
.
Looking into de source code I see that both functions call checkAsync
which accepts bot passes
and fails
functions but depending on which one called it (fails
or passes
) only one is real and the other is empty.
So I think a new function that allows both fails
and pases
callbacks would be very useful and it would avoid the duplicated validation mentioned in the async scenario.
I modified locally the source to include the next method in validator.js
(the name is my personal suggestion):
/**
* Determine if validation either passes or fails
* @param {function} passes
* @param {function} fails
* @return {boolean|undefined}
*/
test: function(passes,fails) {
var isPassesAsync = this._checkAsync('passes', passes);
var isFailsAsync = this._checkAsync('fails', fails);
if(isPassesAsync && isFailsAsync) {
return this.checkAsync(passes,fails);
}
return this.check();
}
with this method you call it with 2 cb functions, one for each case, and this way the double validation doesn’t occur anymore. Example code:
let validation = new Validator(data,rulesWithAsyncValidators);
validation.test(
() => {
//handle passed validation
},
() => {
//handle failed validation
}
);
What you think? would you add this new method or may I send a PR?
Thank you in advance for your attention and congratulations for such awesome lib!
Issue Analytics
- State:
- Created 6 years ago
- Reactions:1
- Comments:6 (1 by maintainers)
Top GitHub Comments
Meh. I think this just overcomplicates the library adding yet another way to validate data. There is no real benefit to type checking the
checkAsync
method as it’s name inherently implies that promises need to be supplied.I am facing same issue. Is there any solution yet?