Strickland
Search…
Async Validation
If you have wondered how async validation works with Strickland, you will be delighted at how simple it is: a validator can use a Promise.
Similar to how validate normalizes a boolean into validation result with an isValid property, a Promise is normalized into a validation result with a validateAsync property. The normalized validateAsync property is a function that returns a Promise resolving to the async result.
Let's take a look at a usernameIsAvailable validator. Just like synchronous validators, async validators can resolve to either boolean results or validation results with isValid properties.
1
import validate from 'strickland';
2
3
function usernameIsAvailable(username) {
4
return new Promise((resolve) => {
5
if (username === 'marty') {
6
// Resolve to an invalid validation result object
7
resolve({
8
isValid: false,
9
message: `"${username}" is not available`
10
});
11
}
12
13
// Resolve to a boolean
14
resolve(true);
15
});
16
}
17
18
const result = validate(usernameIsAvailable, 'marty');
19
20
result.validateAsync().then((asyncResult) => {
21
/*
22
asyncResult = {
23
isValid: false,
24
value: 'marty',
25
message: '"marty" is not available'
26
}
27
*/
28
});
Copied!
When a validator returns a Promise, the normalized validation result will include isValid: false to indicate that the result is not (yet) valid.
Last modified 1yr ago
Copy link