-
-
Notifications
You must be signed in to change notification settings - Fork 616
/
standard-validation.ts
27 lines (24 loc) · 960 Bytes
/
standard-validation.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { Meta, StandardValidator } from '../base';
import { toString as toStringImpl } from '../utils';
import { Context } from '../context';
import { ContextItem } from './context-item';
export class StandardValidation implements ContextItem {
message: any;
constructor(
private readonly validator: StandardValidator,
private readonly negated: boolean,
private readonly options: any[] = [],
// For testing only.
// Deliberately not calling it `toString` in order to not override `Object.prototype.toString`.
private readonly stringify = toStringImpl,
) {}
async run(context: Context, value: any, meta: Meta) {
const values = Array.isArray(value) ? value : [value];
values.forEach(value => {
const result = this.validator(this.stringify(value), ...this.options);
if (this.negated ? result : !result) {
context.addError({ type: 'field', message: this.message, value, meta });
}
});
}
}