-
-
Notifications
You must be signed in to change notification settings - Fork 173
/
dependent.js
executable file
·79 lines (67 loc) · 1.95 KB
/
dependent.js
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { getProperties, getWithDefault, get } from '@ember/object';
import { assert } from '@ember/debug';
import { isPresent, isEmpty, isNone } from '@ember/utils';
import { isArray, A } from '@ember/array';
import Base from 'ember-cp-validations/validators/base';
/**
* <i class="fa fa-hand-o-right" aria-hidden="true"></i> [See All Options](#method_validate)
*
* Defines an attribute as valid only if its dependents are valid.
*
* ## Example
*
* ```javascript
* // Full name will only be valid if firstName and lastName are filled in
* validator('dependent', {
* on: ['firstName', 'lastName']
* })
* ```
*
* @class Dependent
* @module Validators
* @extends Base
*/
const Dependent = Base.extend({
/**
* @method validate
* @param {Any} value
* @param {Object} options
* @param {Array} options.on Attributes this field is dependent on
* @param {Object} model
* @param {String} attribute
*/
validate(value, options, model, attribute) {
let { on, allowBlank } = getProperties(options, ['on', 'allowBlank']);
assert(
`[validator:dependent] [${attribute}] option 'on' is required`,
isPresent(on)
);
if (isNone(model)) {
return true;
}
if (allowBlank && isEmpty(value)) {
return true;
}
let dependentValidations = getWithDefault(options, 'on', A()).map(
dependent => get(model, `validations.attrs.${dependent}`)
);
if (!isEmpty(dependentValidations.filter(v => get(v, 'isTruelyInvalid')))) {
return this.createErrorMessage('invalid', value, options);
}
return true;
}
});
Dependent.reopenClass({
getDependentsFor(attribute, options) {
let dependents = get(options, 'on');
assert(
`[validator:dependent] [${attribute}] 'on' must be an array`,
isArray(dependents)
);
if (!isEmpty(dependents)) {
return dependents.map(dependent => `${dependent}.isTruelyValid`);
}
return [];
}
});
export default Dependent;