-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathtype.js
103 lines (94 loc) · 2.61 KB
/
type.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
98
99
100
101
102
103
module.exports = function() {
/**
* Rule for validating a value type.
*/
this.type = function type() {
var id = this.rule.type
, Type = this.rule.Type
, invalid = false;
// instanceof comparison on `type` as function
if(typeof(Type) === 'function') {
if(!(this.value instanceof Type)) {
this.raise(
this.reasons.instance,
this.messages.types.instance,
this.field, Type.name || 'function (anonymous)');
}
}else if(id === 'null') {
invalid = this.value !== null;
}else if(id === 'regexp') {
if(!(this.value instanceof RegExp)) {
try {
new RegExp(this.value);
}catch(e) {
invalid = true;
}
}
}else if(id === 'string') {
invalid = typeof this.value !== 'string' && this.validates();
}else if(id === 'object') {
invalid = (typeof(this.value) !== 'object'
|| Array.isArray(this.value));
}else if(id === 'array') {
invalid = !Array.isArray(this.value);
}else if(id === 'float') {
invalid = typeof(this.value) !== 'number'
|| Number(this.value) === parseInt(this.value);
}else if(id === 'integer') {
invalid = typeof(this.value) !== 'number'
|| Number(this.value) !== parseInt(this.value);
// straight typeof test
}else{
invalid = typeof(this.value) !== id;
}
if(invalid) {
this.raise(
this.reasons.type,
this.messages.types[this.rule.type],
this.field, this.rule.type);
}
}
/**
* Validate an array of types using logical or.
*
* @param cb Callback function.
*/
function types(cb) {
var list = this.rule.type.slice(0)
, i
, type
, length = this.errors.length
, invalid;
if(this.validates()) {
this.required();
for(i = 0;i < list.length;i++) {
type = list[i];
delete this.rule.Type;
if(typeof type === 'function') {
this.rule.Type = type;
}
this.rule.type = type;
this.type();
}
invalid = (this.errors.length - length) === list.length;
// remove raised errors
this.errors = this.errors.slice(0, length);
// all of the type tests failed
if(invalid) {
this.raise(
this.reasons.type,
this.messages.types.multiple,
this.field,
list.map(function(type) {
if(typeof(type) === 'function') {
return type.name || 'function (anonymous)';
}
return type;
}).join(', ')
)
}
}
cb();
}
this.main.types = types;
}