UNPKG

1.11 kBJavaScriptView Raw
1var rsvp = require('rsvp');
2
3
4var Valida = function() {
5 this.validators = {};
6 this.sanitizers = {};
7};
8
9
10/**
11 * fn won't be called in case value is undefined.
12 *
13 * fn = (ctx, options, value, [cb])
14 */
15Valida.prototype.setValidator = function(key, fn) {
16 this.validators[key] = fn;
17};
18
19
20Valida.prototype.setValidators = function(set) {
21 for (var key in set) {
22 this.setValidator(key, set[key]);
23 }
24};
25
26/**
27 * fn = (ctx, options, value, [cb])
28 */
29Valida.prototype.setSanitizer = function(key, fn) {
30 this.sanitizers[key] = fn;
31};
32
33
34Valida.prototype.setSanitizers = function(set) {
35 for (var key in set) {
36 this.setSanitizer(key, set[key]);
37 }
38};
39
40
41Valida.prototype.process = function(obj, schema, cb, groups) {
42 var deferred = rsvp.defer();
43
44 if (typeof cb !== 'function') {
45 groups = cb;
46
47 cb = function (err, ctx) {
48 if (err) return deferred.reject(err);
49
50 deferred.resolve(ctx);
51 };
52 }
53
54 var ctx = new Valida.Context(this, obj, schema, cb, groups);
55 ctx.run();
56
57 return deferred.promise;
58};
59
60
61Valida.Context = require('./context');
62
63
64module.exports = new Valida();