1 |
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 | const Base = require('./Validator');
|
7 |
|
8 | module.exports = class RangeValidator extends Base {
|
9 |
|
10 | constructor (config) {
|
11 | super({
|
12 | range: null,
|
13 | not: false,
|
14 | allowArray: false,
|
15 | ...config
|
16 | });
|
17 | if (!Array.isArray(this.range)) {
|
18 | throw new Error('Range property must be array');
|
19 | }
|
20 | }
|
21 |
|
22 | getMessage () {
|
23 | return this.createMessage(this.message, 'Invalid range');
|
24 | }
|
25 |
|
26 | validateValue (value) {
|
27 | if (Array.isArray(value) && !this.allowArray) {
|
28 | return this.getMessage();
|
29 | }
|
30 | let inRange = true;
|
31 | const values = Array.isArray(value) ? value : [value];
|
32 | for (const item of values) {
|
33 | if (!this.range.includes(item)) {
|
34 | inRange = false;
|
35 | break;
|
36 | }
|
37 | }
|
38 | return this.not !== inRange ? null : this.getMessage();
|
39 | }
|
40 | }; |
\ | No newline at end of file |