-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsanidator.js
73 lines (61 loc) · 1.65 KB
/
sanidator.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
var HashKeySanidator = require('./hashKeySanidator')
/**
* Simple value sanidation
*/
var Sanidator = module.exports = function (v) {
this.value = v
}
Sanidator.prototype = {
// Defines the error message for this validation
err:function (msg) {
this.error = (this.overrideError || msg || 'invalid_value')
throw this.error
},
// Skips all other validations
skip:function () {
this.skipped = true
throw 'skipping_other_validations'
},
// Overrides next error message
msg:function (msg) {
this.overrideError = msg
return this;
},
// Either defines or returns the value being sanitized
val:function (v) {
if (v === undefined) return this.value
this.value = v
}
}
/**
* Filters
*/
Sanidator.filters = {}
// Sets a filter for the sanidator
Sanidator.setFilter = function (name, func) {
Sanidator.filters[name] = function (v, a, b, c) {
var vs = new Sanidator(v)
try {
return func.call(vs, v, a || {}, b, c)
} catch (e) {
if (vs.error || vs.skipped) {
return vs.error
} else {
throw e
}
}
}
HashKeySanidator.prototype[name] = Sanidator.prototype[name] = function (a, b, c) {
var error = func.call(this, this.value, a || {}, b, c)
if (error) {
this.err(typeof error == 'string' ? error : undefined)
}
// this.overrideError = undefined
return this;
}
};
Sanidator.setFilters = function (filters) {
for (var name in filters) {
Sanidator.setFilter(name, filters[name]);
}
}