UNPKG

2.2 kBJavaScriptView Raw
1/**
2 * @copyright Copyright (c) 2019 Maxim Khorin <maksimovichu@gmail.com>
3 */
4'use strict';
5
6const Base = require('./Validator');
7
8module.exports = class EachValidator extends Base {
9
10 constructor(config) {
11 super({
12 rule: null,
13 allowRuleMessage: true,
14 ...config
15 });
16 this._validator = null;
17 }
18
19 getMessage () {
20 return this.createMessage(this.message, 'Invalid value');
21 }
22
23 getValidator (model) {
24 if (this._validator === null) {
25 this._validator = this.createEmbeddedValidator(model);
26 }
27 return this._validator;
28 }
29
30 createEmbeddedValidator (model) {
31 if (this.rule instanceof Base) {
32 return this.rule;
33 }
34 if (!(model instanceof Model)) {
35 model = this.spawn(Model); // mock up context model
36 }
37 return this.constructor.createValidator(this.rule, model, this.attrs, this.params);
38 }
39
40 async validateAttr (attr, model) {
41 const values = model.get(attr);
42 const validator = this.getValidator();
43 if (!(validator instanceof FilterValidator && Array.isArray(values))) {
44 this.getValidator(model); // ensure model context while validator creation
45 return super.validateAttr(...arguments);
46 }
47 const filteredValues = [];
48 model.set(attr, filteredValues);
49 for (const value of values) {
50 if (!(Array.isArray(value) && validator.skipOnArray)) {
51 filteredValues.push(await validator.filter(value, attr, model));
52 }
53 }
54 }
55
56 async validateValue (values) {
57 if (!Array.isArray(values)) {
58 return this.getMessage();
59 }
60 const validator = this.getValidator();
61 for (const value of values) {
62 const result = await validator.validateValue(value);
63 if (result) {
64 return this.allowRuleMessage ? result : this.getMessage();
65 }
66 }
67 }
68};
69
70const Model = require('../base/Model');
71const FilterValidator = require('./FilterValidator');
\No newline at end of file