1 |
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 | const Base = require('./Validator');
|
7 |
|
8 | module.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);
|
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);
|
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 |
|
70 | const Model = require('../base/Model');
|
71 | const FilterValidator = require('./FilterValidator'); |
\ | No newline at end of file |