-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhashKeySanidator.js
78 lines (70 loc) · 2.19 KB
/
hashKeySanidator.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
// Validates and sanitizes a key in a HashSanidator
var HashKeySanidator = module.exports = function (hashSanidator, name) {
this.name = name
this.hash = hashSanidator.hash
this.hashSanidator = hashSanidator
this.value = this.hash[this.name]
}
HashKeySanidator.prototype = {
// Applies a rule with filters to the value being validated
sanidate:function (rule) {
if (typeof rule == 'object') {
var r = rule
rule = function () {
this.rules(r)
}
}
if (typeof rule == 'function') {
try {
var error = rule.call(this, this.hash[this.name], this.hash);
} catch (e) {
if (this.error || this.skipped) {
return this
} else {
throw e
}
}
if (typeof error == 'string') {
this.error = error
}
}
return this;
},
// 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'
},
overrideError:null,
// 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.hash[this.name]
this.value = this.hash[this.name] = v
return this;
},
nestedSanidator:function () {
var self = this
if (!this.hashSanidator._nestedInstances[this.name]) {
this.hashSanidator._nestedInstances[this.name] =
new (require('./hashSanidator'))(
this.val(),
{
err:function (param, msg) {
self.hashSanidator.err(self.name + '.' + param, msg)
}
}
)
}
return this.hashSanidator._nestedInstances[this.name]
}
}