This repository has been archived by the owner on Sep 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
rule-validator-0.3.1.js
86 lines (74 loc) · 2.35 KB
/
rule-validator-0.3.1.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
(function () {
var tv4,
__,
ruleValidator = {};
if (typeof(module) !== 'undefined' && module.exports) {
tv4 = require('tv4');
__ = require('lodash');
module.exports = ruleValidator;
} else if (typeof(define) !== 'undefined') {
define(['amanda', 'underscore'], function (amanda, underscore) {
tv4 = tv4;
__ = underscore;
return ruleValidator;
});
} else {
tv4 = tv4;
__ = _;
this.ruleValidator = ruleValidator;
}
var ValidationRules = {};
ValidationRules.prototype = {
// __validate:__ Use this function validate some data against a rule.
//
// `rules.validate(ruleName, data, callback)`
//
// - __ruleName:__ The rule that should be used.
// - __data:__ The data that should be validated.
// - __callback:__ `function(err){}`
validate: function(ruleName, data, callback) {
if (this[ruleName]) {
var validation = tv4.validateResult(data, this[ruleName]);
if (!validation.valid) {
if (validation.error.subErrors && validation.error.subErrors.length > 0) {
validation.error.subErrors = __.sortBy(validation.error.subErrors, function(s) {
return -s.code;
});
callback(validation.error.subErrors[0].dataPath + ' => ' + validation.error.subErrors[0].message);
} else {
callback(validation.error.dataPath + ' => ' + validation.error.message);
}
} else {
callback(null);
}
} else {
callback(null);
}
}
};
// __extend:__ Use this function to create your rule validator object.
//
// `base.extend(rules, extension)`
//
// - __rules:__ The rules that should be used.
// - __extension:__ The rest that you want to extend. (Special handling for attributes!)
ruleValidator.extend = function(rules, extension) {
var extObj = __.extend(__.clone(ValidationRules.prototype), extension);
for (var r in rules) {
var rule = rules[r];
if (rule.type === 'object' && rule.properties) {
extObj[r] = rule;
} else {
extObj[r] = {
type: 'object',
properties: rule
};
}
extObj[r].ruleName = r;
extObj[r].validate = function(data, callback) {
extObj.validate(this.ruleName, data, callback);
};
}
return extObj;
};
}());