/
validateProperty.js
97 lines (82 loc) · 2.31 KB
/
validateProperty.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/**
* Validation.validateProperty
*
* @param {string} propertyName
* @param {object} propertyAttributes
* @param {string|object} propertyValue
* @param {boolean} singleError
* @param {function} callback
*/
Validation.prototype.validateProperty = function(property, propertyValue, propertyAttributes, callback) {
// Save a reference to the ‘this’
var self = this;
var context = {};
[
'validateItems',
'validateProperties',
'validateSchema',
'validateProperty',
'getProperty',
'attributes',
'errors',
'joinPath'
].forEach(function(key) {
context[key] = this[key];
}, self);
/**
* Iterator
*
* @param {string} attributeName
* @param {function} attributeFn
* @param {function} callback
*/
var iterator = function(attributeName, attributeFn, callback) {
var lastLength = self.errors.length;
// Overwrite the ‘addError’ method
context.addError = function(message) {
if (isObject(message)) {
return self.errors.push({
property: message.property || property,
propertyValue: message.propertyValue || propertyValue,
attributeName: message.attributeName || attributeName,
attributeValue: message.attributeValue || propertyAttributes[attributeName],
message: message.message || undefined
});
}
return self.errors.push({
property: property,
propertyValue: propertyValue,
attributeName: attributeName,
attributeValue: propertyAttributes[attributeName],
message: message
});
};
/**
* OnComplete
*/
var onComplete = function() {
if (self.errors.length > lastLength && self.singleError) {
return callback(true);
} else {
return callback();
}
};
if (isDefined(propertyAttributes[attributeName])) {
return attributeFn.apply(context, [
property,
propertyValue,
propertyAttributes[attributeName],
propertyAttributes,
onComplete
]);
} else {
return callback();
}
};
// If it's not a required param and it's empty, skip
if (propertyAttributes.required !== true && isUndefined(propertyValue)) {
return callback();
}
// Validate the property
return each(self.attributes, iterator, callback);
};