-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
97 lines (77 loc) · 2.13 KB
/
index.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
/**
* Expose `validate`.
*/
module.exports = validate;
/**
* Return a `plugin` function with `options`.
*
* @param {Object} options (optional)
*/
function validate (options) {
options = options || {};
return function plugin (Model) {
/**
* Global validators.
*/
Model.validators = [];
/**
* Add a validator `fn` to the Model with optional `attr` scope.
*
* @param {String} attr (optional)
* @param {Function} fn
*/
Model.validator = function (attr, fn) {
if ('function' == typeof attr) fn = attr, attr = null;
if (attr) {
var schema = this.attrs[attr];
if (!schema) throw new Error('unrecognized attribute "' + attr + '"');
schema.validators = schema.validators || [];
schema.validators.push(fn);
} else {
this.validators.push(fn);
}
return this;
};
/**
* Mark as `attr` as invalid with a `message` and optional `context`.
*
* @param {String} attr
* @param {String} message
* @param {Object} context (optional)
* @return {Model}
*/
Model.prototype.invalid = function (attr, message, context) {
context = context || {};
context.attr = attr;
context.message = message;
this.errors = this.errors || [];
this.errors.push(context);
return this;
};
/**
* Perform validations, and return a boolean of whether the model is
* valid or not.
*
* @return {Boolean}
*/
Model.prototype.validate = function () {
var fns = this.Model.validators;
this.errors = [];
// global
for (var i = 0, fn; fn = fns[i]; i++) fn(this);
// attribute-specific
for (var key in this.Model.attrs) {
var schema = this.Model.attrs[key];
var vals = schema.validators;
var value = this.attrs[key];
if (!vals) continue;
for (var j = 0, val; val = vals[j]; j++) {
var valid = val(value);
if (valid) continue;
this.invalid(key, '"' + key + '" is invalid', { value: value });
}
}
return ! this.errors.length;
};
};
}