-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
74 lines (56 loc) · 1.38 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
/**
* Module dependencies.
*/
var JSV = require('JSV').JSV
, each = require('each')
, bind = require('bind');
/**
* Module exports.
*/
module.exports = SchemaValidate;
/**
* Initialize new validator.
*/
function SchemaValidate() {
// make this callbable as function
if (!(this instanceof SchemaValidate)) return new SchemaValidate();
var self = this;
this.env = JSV.createEnvironment();
// return real validator function
return function(Model){
Model.validate(bind(self, self.validate, Model));
};
}
/**
* Validator function called with the model class as context.
*
* @param {Model} Model the class
* @param {Object} model the instance
*
* @api private
*/
SchemaValidate.prototype.validate = function(Model, model){
var env = this.env;
// check each attribute with the associated schema
each(Model.attrs, function(attr, schema){
var value = model[attr]()
, report;
report = env.validate(value, schema);
registerErrors(model, attr, report);
});
};
/**
* Registers the errors included in the report as model errors.
*
* @param {Model} model the model instance
* @param {String} attr the attribute the errors refer to
* @param {Report} report the jsv report
*
* @api private
*/
function registerErrors(model, attr, report) {
each(report.errors, function(error){
// register the error
model.error(attr, error);
});
}