api-validate
v1.0.5
Published
request params validate
Downloads
5
Maintainers
Readme
api-validate
简单的参数验证,验证接口端收到的数据
var v = require('api-validate');
var rule = {
name : {type:'string',match:/tjay/,required:true,msg:'name error'},
age : {type:'number',min:1,max:130,required:true,msg:'age error'}//...
}
v.validate(rule,{
name:'tjay',
age:20
});// return => [] no error return empty array
v.validate(rule,{
name:'tjay1',
age:-1
});// return => ['name error','age error'] has error return message array
//define diy rule function
v.define('myRuleName',function(arg){
return function(value){
return value==null || value == arg;
};
});
var rule2 = {
//msg is message alias,'the Value' is function arg,multi args use [arg1,arg2....]
name : {type:'string',myRuleName:'the Value',msg:'you error'}
}
v.validate(rule2,{
name:'tjay1'
});// return => ['you error']
v.validate(rule2,{
name:null
});// return => []
v.validate(rule2,{
name:'the Value'
});// return => []
//use in express
app.post('/addUser',v.connectValidate(rule2),function(req,res,next){
//if validate success,the request params in req.validatedParams , if validate fail call next(err)
var params = req.validatedParams;
userModel.save(params).then(function(){
res.end('success');
}).catch(function(err){
next(err);
});
});