# new AsyncValidator()
Abstract class for defining asynchronous validators.
Abstract class for defining asynchronous validators.
This class extends the base Validator
and enforces that any implementation
of hasErrors
must be asynchronous, always returning a Promise.
Use this when the validation process involves asynchronous operations, such as API calls, database lookups, or time-based checks (e.g., timeouts).
- See:
-
Validator
For the base synchronous validator.
View Source validation/Validators/AsyncValidator.ts, line 57
Example
```typescript
// Example of an asynchronous validator that compares value against a timeout
class TimeoutValidator extends AsyncValidator<{ timeout?: number }> {
constructor(message: string = "Validation failed due to timeout") {
super(message);
}
async hasErrors(value: number, options?: { timeout?: number }) {
const delay = options?.timeout ?? 100;
// async call
await new Promise(res => setTimeout(res, delay));
if (value > delay) {
// Rejects the validation after waiting the delay if value is greater
return Promise.resolve(this.getMessage());
}
// Passes the validation after waiting the delay
return Promise.resolve(undefined);
}
}
// Example usage:
const validator = new TimeoutValidator();
async function runValidation() {
const error = await validator.hasErrors(50, { timeout: 100 });
if (error) {
return console.error('Validation error:', error);
}
console.log('Value is valid');
}
await runValidation();
```
- If `value > timeout`, the validator waits for the delay and then rejects with an error.
- If `value <= timeout`, the validator waits for the delay and resolves successfully with `undefined`.
Classes
- AsyncValidator
- Abstract class for defining asynchronous validators.
Methods
# abstract hasErrors(value, optionsopt, proxy)
Asynchronously validates a value.
Asynchronously validates a value.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
value |
any
|
The value to validate |
|
options |
V
|
<optional> |
Optional configuration options for customizing validation behavior |
proxy |
PathProxy.<any>
|
Promise<string | undefined> Error message if validation fails, undefined if validation passes