validate koa request params and format request params
Installation
$ npm install koa-validate --save
Basic usage:
'use strict';varkoa=require('koa');varapp=koa();varrouter=require('koa-router')();require('koa-validate')(app);app.use(require('koa-body')({multipart:true,formidable:{keepExtensions:true}}));app.use(router.routes()).use(router.allowedMethods());router.post('/signup',function*(){//optional() means this param may not in the params.this.checkBody('name').optional().len(2,20,"are you kidding me?");this.checkBody('email').isEmail("your enter a bad email.");this.checkBody('password').notEmpty().len(3,20).md5();//empty() mean this param can be a empty string.this.checkBody('nick').optional().empty().len(3,20);//also we can get the sanitized value varage=this.checkBody('age').toInt().value;yieldthis.checkFile('icon').notEmpty().size(0,300*1024,'file too large').move("/static/icon/",function*(file,context){//resize image});if(this.errors){this.body=this.errors;return;}});router.get('/users',function*(){this.checkQuery('department').empty().in(["sale","finance"],"not support this department!").len(3,20);this.checkQuery('name').empty().len(2,20,"bad name.").trim().toLow();this.checkQuery('age').empty().gt(10,"too young!").lt(30,"to old!").toInt();if(this.errors){this.body=this.errors;return;}});router.get('/user/:id',function*(){this.checkParams('id').toInt(0);if(this.errors){this.body=this.errors;return;}});//json body,we can check it using [json path](https://github.com/flitbit/json-path)(like xpath)router.post('/json',function*(){this.checkBody('/store/book[0]/price').get(0).eq(8.95);this.checkBody('#/store/book[0]/category').first().trim().eq('reference');if(this.errors){this.body=this.errors;return;}})app.listen(3000);
API
checkBody,checkQuery,checkParams will return a Validator instance.
when use require('koa-validate')(app) ,the request context will bind the method:
checkBody(fieldName,[transFn]) - check POST body.,transFn see json-path.it will not use json path if transFn is false.
checkQuery(fieldName,[transFn]) - check GET query.,transFn see json-path.it will not use json path if transFn is false.
checkParams(fieldName) - check the params in the urls.
checkFile(fieldName,[deleteOnCheckFailed]) - check the file object, if you use koa-body.this function will return FileValidator object. deleteOnCheckFailed default value is true
checkHeader(fieldName) - check the params in the request http header.
replace(regexp|substr, newSubStr|function) - the same as String replace
clone(newKey,[newValue]) - clone current value to the new key, if newValue supplied , use it. eg. this.checkBody('v1').clone('md5').md5(); then your can use this.request.body.md5.
encodeBase64() - encode current value to base64 string.
decodeBase64([inBuffer],[tip]) - decode current base64 to a normal string,if inBuffer is true , the value will be a Buffer.
hash(alg , [encoding]) - hash current value use specified algorithm and encoding(if supplied , default is 'hex'). ref hash
md5() - md5 current value into hex string.
sha1() - sha1 current value into hex string.
For json path:
check(fn,tip,scope) - if fn return false then check failed.fn format function(value,key,requestParams):boolean
filter(fn,scope) - filter the value if value is array.fn format function(value,index,key,requestParams):boolean
get(index) - change the value to the specified index value
first() - get the first value!
FileValidator:
Validators:
empty() - current file field can to be a empty file.
notEmpty([tip]) - current file field can not to be a empty file.
size(min,max,[tip]) - limit the file size.
contentTypeMatch(reg,[tip]) - check the file's contentType with regular expression.
isImageContentType([tip]) - check the file's contentType if is image content type.
fileNameMatch(reg,[tip]) - check the file's name with regular expression.
suffixIn(arr,[tip]) - check the suffix of file's if in specified arr. arr eg. ['png','jpg']
Sanitizers:
File sanitizers are generators,we should use yield to execute them. eg. yield this.checkFile('file').notEmpty().copy('/');
move(target,[afterMove]) - move upload file to the target location. target can be a string or function or function*.if target end with '/' or '\',the target will be deemed as directory.
target function interface:string function(fileObject,fieldName,context).this function will return a string of the target file.
afterMove:it can be a function or function*.interface:function(fileObject,fieldName,context)
copy(target,[afterCopy]) - move upload file to the target location. target can be a string or function or function*. target function interface:function (fileObject,fieldName,context) .
afterCopy:it can be a function or function*.interface:function(fileObject,fieldName,context)
delete() - delete upload file.
How to extends validate:
varValidator=require('koa-validate').Validator;// to do what you want to.//you can use this.key ,this.value,this.params,this.context,this.exists//use addError(tip) , if you meet error.
请发表评论