Skip to content

Commit

Permalink
fix: support asynchrone rules
Browse files Browse the repository at this point in the history
Validator#validate is now asynchrone
  • Loading branch information
hecht-a committed Dec 20, 2022
1 parent d997d21 commit 48c726e
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions src/Validator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
type CallableRule = ((data: string, ...args: unknown[]) => boolean);
type CallableRule = ((data: string, ...args: unknown[]) => boolean | Promise<boolean>);

type Rule = {
cb: CallableRule,
Expand Down Expand Up @@ -93,24 +93,26 @@ export class Validator {
* @param {string} fieldValue
* @private
*/
private runValidator(cbName: string, field: string, fieldValue: string): void {
private async runValidator(cbName: string, field: string, fieldValue: string): Promise<void> {
const rule = this.rules[cbName];

if (rule.cb(fieldValue, ...rule.optionalParams ?? [])) {
if (await rule.cb(fieldValue, ...rule.optionalParams ?? [])) {
this.addError(field, this._errorMessages[cbName]);
}
}

/**
* Check the form validity
*/
public validate(): void {
public async validate(): Promise<void> {
for (const field in this._rulesMapping) {
this._rulesMapping[field].forEach((cbName) => {
for (const cbName of this._rulesMapping[field]) {
const fieldValue = this.form.get(field);

this.runValidator(cbName, field, fieldValue ? fieldValue.toString() : "");
});
await this.runValidator(cbName, field, fieldValue
? fieldValue.toString()
: "");
}
}
}

Expand Down

0 comments on commit 48c726e

Please sign in to comment.