rocksonzeta / koa-validate Goto Github PK
View Code? Open in Web Editor NEWvalidate koa request params and format request params
Home Page: https://github.com/RocksonZeta/koa-validate
License: MIT License
validate koa request params and format request params
Home Page: https://github.com/RocksonZeta/koa-validate
License: MIT License
if I do
this.checkBody('value').notEmpty('value is empty').toBoolean()
and the value passed in is a boolean of false.
I get a "value is empty" returned.
Seems like it's not the behaviour you might want.
How would you invalidate if the body of the request has unnecessary keys?
When the checked field's length is greater than the max length, it will cause the same error the checked field's length equal or great than the min
which should be the checked field's length equal or small than the max
.
when i post a param i get this.body == undefined
Is it an error in basic usage code?
If I want to ensure a parameter is 0-100 chars long with .isLength(0, 100)
, isn't this line messing that up?
Line 123 in 0a95252
Example: this.checkBody('markup').trim().isLength(0, 100)
will always trigger isLength error when { markup: '' }. optional()
didn't change anything.
When calling isFloat
, the library checks whether the object is already a number. But when calling toFloat
the library doesn't check that, so passing a number to v.toFloat
will result in TypeError: This library (validator.js) validates strings only
.
It may not be a big problem, since we should know the type of each object before validating.
Just a disclaimer for future users. Source : 0 answer to tickets, 0 PR merged and 0 commits in 2017 and 2018, no support for Koa 2
Supposed I want to validate a sub-element like:
{address:
{street: "Millerstreet"}
}
My check
this.checkBody('address.street').notEmpty()
does not seem to work.
Is it even possible to validate sub-elements with koa-validate?
Or have I simply missed something?
I know this question may not belong here but I will ask anyway.
In order to test this I have had to use supertest, which is more of an integration test. The problem I am having is trying to figure out how to emulate the 'koa context' in order to test it because the validator is attached to the context in the middleware. I really like this validator and don't want to move to another one, so any suggestions would be great. Thanks!
how do you check a body parameter is actually string, rather than number or null or object?
app.post('/', function*() {
this.checkBody('test').notEmpty().decodeURIComponent().isUrl();
})
$ http --form POST localhost:3000 test=%
URIError: URI malformed
When using jsonpath, the library still uses key in body
to determine whether given key exists.
return new Validator(this, key, getValue(body,key,transFn), key in body , body);
Therefore, with a body like this:
{"foo":{"bar":"hello world"}}
Following code will return an error:
this.checkBody('/foo/bar', true).first().exist()
Because the property is marked as exists:false
.
I just copied the sample code in read me but got this error:
TypeError: this.checkFile(...).notEmpty(...).size is not a function
at Object.<anonymous> (/Applications/MAMP/htdocs/nia/test.js:21:45)
at next (native)
at Object.dispatch (/Applications/MAMP/htdocs/nia/node_modules/koa-router/lib/router.js:331:14)
at next (native)
at onFulfilled (/Applications/MAMP/htdocs/nia/node_modules/koa/node_modules/co/index.js:65:19)
at /Applications/MAMP/htdocs/nia/node_modules/koa/node_modules/co/index.js:54:5
at Object.co (/Applications/MAMP/htdocs/nia/node_modules/koa/node_modules/co/index.js:50:10)
at Object.toPromise (/Applications/MAMP/htdocs/nia/node_modules/koa/node_modules/co/index.js:118:63)
at next (/Applications/MAMP/htdocs/nia/node_modules/koa/node_modules/co/index.js:99:29)
at onFulfilled (/Applications/MAMP/htdocs/nia/node_modules/koa/node_modules/co/index.js:69:7)
Am I missing something? Here is my final code:
'use strict';
var koa = require('koa');
var app = koa();
app.use(require('koa-body')());
app.use(require('koa-validate')());
var router = require('koa-router')();
router.get('/upload', function *(){
this.body = '<form action="/upload" enctype="multipart/form-data" method="post">'+
'<input type="text" name="title"><br>'+
'<input type="file" name="file" ><br>'+
'<input type="submit" value="Upload">'+
'</form>'
} );
router.post('/upload', function * () {
//optional() means this param may not in the params.
yield this.checkFile('file').notEmpty().size(0,300*1024,'file too large').move("/static/icon/" , function*(file,context){
//resize image
});
if (this.errors) {
this.body = this.errors;
return;
}
this.body = this.request.body;
});
app
.use(router.routes())
//.use(router.allowedMethods());
app.listen(3000);
Here are some validators I use in my project that I think should belong to koa-validate.
notMatch
- inverse of match
ensure
- executes arbitrary expression. if falsey, then error. (koa-validate needs a generic validator for arbitrary expressions)
this.checkBody('username')
.notEmpty('Username required')
.ensureNot(yield db.findUserByUsername(this.request.body.username), 'Username taken')
ensureNot
(or perhaps refute
) - inverse of ensure
Implementations:
// Ensure that a string does not match the supplied regular expression.
Validator.prototype.notMatch = function(reg, tip) {
if (this.goOn && reg.test(this.value)) {
this.addError(tip || this.key + ' is bad format.');
}
return this;
};
// Ensure that `assertion`, an arbitrary value, is falsey.
Validator.prototype.ensureNot = function(assertion, tip, shouldBail) {
if (shouldBail) this.goOn = false;
if (this.goOn && !!assertion) {
this.addError(tip || this.key + ' failed an assertion.');
}
return this;
};
// Ensure that `assertion`, an arbitrary value, is truthy.
Validator.prototype.ensure = function(assertion, tip, shouldBail) {
if (shouldBail) this.goOn = false;
if (this.goOn && !assertion) {
this.addError(tip || this.key + ' failed an assertion.');
}
return this;
};
edit: ignore shouldBail
https://github.com/RocksonZeta/koa-validate/blob/master/lib/validate.js#L396-L397
Shouldn't the tip be passed to .isInt, not hasError?
yield this.validateBody({ password: 'required', email_id: 'required' });
trying to validate the request body but when everything is in it, it still says Fields are required. everything is in it.
node 12.20.0
koa-validation 0.1.9
This is my code
const getValidation = function* (next) {
this.checkQuery('limit').optional().len(1, 100).trim().toInt()
this.checkQuery('offset').optional().len(1, 100).trim().toInt()
if (this.errors) {
this.status = 400
this.body = this.errors
return
}
yield next
}
router.get('/something', getValidation, Ctrl.get)
When I send GET without offset
query params, It will populate error with TypeError: This library (validator.js) validates strings only
. If I did something wrong just point me to correct please. Thank you.
it would be nice if it possible to validate array of object, for example somebody post something like this:
[
{
name:'aa',
age: 23,
tags:['ss','2333']
},
{
name:'bb',
age: 25
},
]
we can use those code to check each object in an array of even nested array
app.use(function*(){
// the "$" indicate this field is in an array;
this.checkBody('$.name').len(2,10);
this.checkBody('$.age').len(2,10);
this.checkBody('$.tags.$').len(1,10);
})
i looked into the code ,there is a
// var opt = opt || {};
it would be useful if i can set type of this.errors( which defaults to an array ), so i don't have to modify the "this.error" object to proper handling or logging;
i remember express-validator can do that;
Hello,
While I was extending this module with a custom validator function I wanted to use the validator module.
I know that a simple npm install --save validator and require would do the job (which I did) but could be nice to export it or to make it available in the object with a variable like this.v or something else.
I am very interested in whether this project is still actively maintained, since it is the most starred validation middleware for koa. I would love to help out and develop some features, but there does not seem to be much activity on reviewing pull request.
ERROR : This affects the package json-ptr before 3.0.0. A type confusion vulnerability can lead to a when the user-provided keys used in the pointer parameter are arrays.
json-ptr is dependency package for json-path version ^0.1.3 which is again a dependency package for Koa-validate package.
I was confused why my validation was throwing an error only to realize I was spelling the toLowerCase() with camelCase instead of lowercases.
Might be helpful for other people just starting with KOA Validate to keep things consistent whereas possible.
does it support koa2 ?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.