-
Notifications
You must be signed in to change notification settings - Fork 4
/
iform.js
276 lines (243 loc) · 6.56 KB
/
iform.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/**
* node-iform
*
* 1. define rules
*
* var userForm = require('iform')({
* username: {
* required : true ,
* len: [3, 7]
* } ,
* password: {
* type: password,
* required: true,
* len : 3
* },
* email : {
* type :'email',
* required : true
* },
* avatar : {
* default : function(req){
* return getAvatar(req.body.email);
* }
* },
* age : Number,
* birth : Date
* });
*
* 2. type
*
* all the type is define in node-validator, Validator.prototype.is*
*
* there are isDate, isEmail, isCreditCard, isUrl, etc
*
* you can use capitalised string or lowercase string. e.g. 'date', 'Email', 'CreditCard', 'url'
*
* 3. rules
*
* all the method in validator.Validator.prototype and validator.prototype.Filter could be use as an rule
*
* you can use the method name as rule name, and set the arguments by rule value, if it takes more than
* 1 argument, use array. like this password:{len:[3, 15]}, if you only want minLength, use password:{len: 3}
*
* 4. extend node-validator
*
* you can extend Validator and Filter by prototype, after this, you must update iform
*
*
* @author Lin Gui
*/
var Validator = require('validator').Validator
, Filter = require('validator').Filter
;
function iForm(rules){
/*
* vars in closure
*/
var ifields = {}
, fieldNames = []
;
/**
* @param {arguments} fields fields will add to req.iform.data
* @return {function} middleware
*/
function middleware(){
var fields = Array.prototype.slice.call(arguments);
if(!fields.length) fields = fieldNames;
return function(req, res, next){
var params = req.body;
var iform = req.iform = {};
var idata = iform.data = {};
var field, field_name, value;
function appendError(msg){
(iform.errors || (iform.errors = {}))[field_name] = msg;
}
// inject node-validator errorHandler
var ivalidator = iValidator(appendError);
for (var i = 0; i < fields.length; i += 1) {
field_name = fields[i];
value = params[field_name];
if(field = ifields[field_name]){
var rules = field.rules;
if(value === undefined) {
// form does not contains
if(rules.required) {
appendError(field_name + ' is required');
}
} else if(value === null || value === '') {
// user leave it blank
if(rules.default){
var v = rules.default;
idata[field_name] = typeof v === 'function' ? v(req) : v;
}
else if(rules.required) {
appendError(field_name + ' is required');
} else {
idata[field_name] = empty(rules.type);
}
} else {
// check the value and convert it
idata[field_name] = field.validate(value, ivalidator);
}
} else {
idata[field_name] = value;
}
};
next();
};
}
/**
* form it self is a middleware, check all req.params
*/
var form = middleware;
// form.fields.username() <==> form.username()
form.fields = ifields;
// init fields
// this must at the bottom of iForm, cause of form[name]
for(var name in rules){
if(rules.hasOwnProperty(name)) {
var rule = rules[name];
if(typeof rule !== 'object'){
rule = {type: rule};
}
var field = ifields[name] = iField(rule);
if(!form[name]) form[name] = field;
fieldNames.push(name);
}
}
return form;
}
/**
* field holder the rules
*/
function iField(rules) {
// alias toHTML
var field = function(){
// TODO toHTML
}
field.validate = function(value, ivalidator, fail_msg){
return ivalidator(value, rules, fail_msg);
}
field.rules = rules;
return field;
}
/**
* generate default empty value if user leave a non-required field blank
*/
function empty(type) {
if(!type) return '';
if(typeof type === 'string') {
switch(type.toLowerCase()) {
case 'int':
case 'decimal':
case 'float':
return 0;
case 'date':
return null;
default:
return ''
}
} else if(type === Number) {
return 0;
} else if(type === Date) {
return null;
} else {
return '';
}
}
/**
* wrap the node-validator
*
* @param {function(msg)} errorHandler
* @return {function}
*/
function iValidator (errorHandler) {
var validator = new Validator()
, filter = new Filter();
if(errorHandler) {
validator.error = errorHandler;
filter.error = errorHandler;
}
/**
* validate value by rules, and convert it
*
* @param {string} value
* @param {object} rules
* @param {string} fail_msg
* @return {*} converted value
*/
return function(value, rules, fail_msg) {
// TODO optimize this, loops, init what need in fields
// FIXME how about sequence check?
validator.check(value, fail_msg);
var type = rules.type;
var f, v;
for(var name in rules) {
// f(v)
(f = ruleValidator[name]) && f.apply(validator, Array.isArray(v = rules[name]) ? v : [v]);
}
if(type && (f=typeValidator[type])) f.apply(validator);
filter.convert(value);
for(var name in rules) {
v = rules[name];
if(typeof v === 'function') {
v.apply(filter);
}
else {
// f(v)
(f = ruleFilter[name]) && f.apply(filter, Array.isArray(v = rules[name]) ? v : [v]);
}
}
if(type && (f=typeFilter[type])) f.apply(validator);
return filter.value();
}
}
// hash Validator Filter methods to use in iValidator
var typeValidator = {}
, ruleValidator = {}
, typeFilter = {}
, ruleFilter = {}
;
/**
* init validator methods hashs
* you must call `update` if you extend node-validator
*/
iForm.update = function() {
for(var name in Validator.prototype) {
if(name.indexOf('is') === 0 && name.length > 2) {
var type = name.slice(2);
typeValidator[type] = typeValidator[type.toLowerCase()] = Validator.prototype[name];
}
ruleValidator[name] = ruleValidator[name.toLowerCase()] = Validator.prototype[name];
}
for(var name in Filter.prototype) {
ruleFilter[name] = ruleFilter[name.toLowerCase()] = Filter.prototype[name];
}
}
ruleValidator[Number] = typeValidator[Number] = Validator.prototype.isDecimal;
ruleValidator[Date] = typeValidator[Date] = Validator.prototype.isDate;
ruleFilter[Number] = typeFilter[Number] = Filter.prototype.toFloat;
iForm.update();
// export iForm
module.exports = iForm;