express-validator / express-validator Goto Github PK
View Code? Open in Web Editor NEWAn express.js middleware for validator.js.
Home Page: https://express-validator.github.io
License: MIT License
An express.js middleware for validator.js.
Home Page: https://express-validator.github.io
License: MIT License
It would be awesome if the library would handle a custom error messages per validator, e.g.
req.assert('email', 'some common message').notEmpty('required').isEmail('valid email required');
So the final message of the validation would be taken from the first validation that failed or the common one if the validator didn't have any.
Line 171 and 173, 'this' is used, but it seems that 'req' would be correct.
Hi,
In below statement
req.assert('[email protected]', 'valid email is required').isEmail();
I have entered a correct e mail still isEmail giving error.
If I am wrong then please correct me.
Thanks
Mohd Siddique Bagwan.
The code is run synchronously with validation. The user data will save even if req.onValidationError
return error.
Here is example of my code.
app.post('/save', function (req, res) {
req.onValidationError(function (msg) {
return msg;
});
//Validate user input
req.assert('email', 'Please enter a valid email').isEmail();
user.collection.save()
});
How to make perform validation asynchronously?
The changelog and your tags are a little outdated too.
Git has a great feature for releases: https://github.com/ctavan/express-validator/releases
You can add tags and easily manage them.
For Example, I have three attributes: tag, keyword, id. I assert one of them is not null. If none of them have value. It's a wrong request.
I look through the README and found nothing about these kind of methods. It's seems I cannot do this kind of check:
req.assert(['id','keyword','tag'], 'One of the ID, Keyword or Tag is required').notNull(1);
If this is impossible, how can I achieve the same goal here?
Is there any way to validate files that has been uploaded? Like size, extensions alowed....?
so, my issue is this. I am using the the validator stuff like "req.assert("gameName", "You must supply a game name").notEmpty();" in one of my controllers. in my test file, i send in req object of {assert: function(x){}, ....} so that in my controller, it can call the assert method. however i keep getting: TypeError: Object has no method 'notEmpty'. so i tried replacing the function with assert(). but then i get: undefined is not equal to true.
so basically my problem is for my testing, how do i pass in the assert method so it works with my controller.
fyi, i am using node.js as my framework, and mocha for testing
I have code like below
req.assert('password', res.__("The password can't be empty).notEmpty();
req.assert('repassword', res.__("Please re-enter the password")).notEmpty();
var errors = req.validationErrors();
console.log(errors);
This will produce result like below
[
{
"param": "password",
"msg": "The password can't be empty,
"value": ""
},
{
"param": "repassword",
"msg": "Please re-enter the password",
"value": ""
}
]
Can I customize this output to specified format like below?
[
{
"param": "password",
"message": "The password can't be empty,
"value": ""
},
{
"param": "repassword",
"message": "Please re-enter the password",
"value": ""
}
],
Is there any options to customize the output?
The current format of the error messages:
[{ param: 'urlparam', msg: 'Invalid urlparam', value: 't1est' } ]
This can only be displayed as text though and I find it very inconvenient to not be able to extract the individual variables from the error message without some intense parsing. Why not offer an error message in JSON format?
I tried using: req.assert('field', 'error').matches(/myregex/);
Is this the right way to call the method 'matches'? Because chriso/validator.js uses matches(str, pattern [, modifiers])
.
using sanitize doesn't work on parameter that are not sent in request. In this example param won't be boolean when it's not part of request.
app.post('/url, function(req, res) {
req.sanitize('param').toBoolean();
}
I want to know if each validation is done in parallel or in series?
Lets use your example
req.checkBody('postparam', 'Invalid postparam').notEmpty().isInt();
req.assert('getparam', 'Invalid getparam').isInt();
req.assert('urlparam', 'Invalid urlparam').isAlpha();
I basically want to know if all of the 3 are run is series or in parallel. I want to do this in parallel as that would make it more fast. I think they are in parallel already but not sure, so asking. Please let me know fast.
If they are not in parallel is it possible to make them parallel using async module?
Seeing as bodyParser() is now deprecated, and not recommended, where does this leave express-validator? Is there any way to use it without the need for bodyParser?
If I pass post and get parameters to an app.post and try and assert values it uses the get parameters.
curl -d 'password=1234567' http://localhost:3000/backend/check/?password=fjf
Password can't be shorter than 6 characters and it throws an exception.
Maybe use a similar syntax to req.param('password', req.body) with req.assert('password)?
I recently installed the most recent release of v1.0.0 from NPM, which appears to have been issued 12 days ago. The expectation is that this would include the checkQuery method that was pushed ~2 months ago.
However, the version being delivered form NPM appears to be an older release, which does not include any recent changes. Did you publish the wrong version/tag perhaps?
Using node v0.11.2 on a mac results in all requests hanging with the following configuration:
var express = require('express')
, http = require('http')
, path = require('path')
, expressValidator = require('express-validator');
var app = express();
app.configure(function() {
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(expressValidator);
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', function(req, res, next) {
res.send(200, {});
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Server running on port " + app.get('port'));
});
If one comments out the express validator middleware it works fine.
Hi @ctavan ,
Is there a way to customize output ?
{ "getparam": "'lab' is invalid" }
instead of
{ param: 'getparam', msg: 'Invalid getparam', value: '1ab' }
thx
I noticed it recently had a version bump and plenty of changes, maybe this should be updated to make use of it?
Strangely enough, though, it seems he removed notEmpty
, notNull
and notContains
.
In addition to that, there is no longer a not
or is
method, but rather a matches
method has been added.
Maybe this means if express-validator does use the updated version, some sort of not
method should be introduced to negate the following validation method?
P.S. I can't for the life of me find the commit with these changes, so apologies if these changes happened a while ago.
_req.sanitize([param...], param)_
Example:
req.sanitize('to', 'title', 'body').escape();
How would I implement a way to validate a password?
The user enters a confirmation password. Should I use a custom filter that compares the two passwords?
While updating all modules for my app it seems for some reason express-form is causing a major error and I have no idea why. It could not even be express-form. Anyways here is the error
TypeError: Object # has no method 'local'
at /Users/tory/Documents/github/tadams/node_modules/express-form/lib/form.js:32:15
at callbacks (/Users/tory/Documents/github/tadams/node_modules/express/lib/router/index.js:165:11)
at param (/Users/tory/Documents/github/tadams/node_modules/express/lib/router/index.js:139:11)
at pass (/Users/tory/Documents/github/tadams/node_modules/express/lib/router/index.js:146:5)
at Router._dispatch (/Users/tory/Documents/github/tadams/node_modules/express/lib/router/index.js:173:5)
at Object.router (/Users/tory/Documents/github/tadams/node_modules/express/lib/router/index.js:33:10)
at next (/Users/tory/Documents/github/tadams/node_modules/express/node_modules/connect/lib/proto.js:190:15)
at Object.methodOverride as handle
at next (/Users/tory/Documents/github/tadams/node_modules/express/node_modules/connect/lib/proto.js:190:15)
at store.get.next (/Users/tory/Documents/github/tadams/node_modules/express/node_modules/connect/lib/middleware/session.js:302:9)
also this repo does not actually exist on github yet as the code is not done...
form(action='/', method='POST')
input(name='company[name]', type='text')
input(name='company[description]', type='text')
input(name='company[address]', type='text')
input(type='submit')
For the above form how can I use the express-validator?
req.assert('company[name]', 'Company Name is required').notEmpty(); doesn't seems to work
Instead of adding the error to req.validationErrors, a validation error in checkHeader will cause an exception.
//name = 'abcd'
req.check('name').isNumeric();
console.log('errors', req.validationErrors());
results in a console output of:
errors [ { param: 'name', msg: 'Invalid number', value: 'abcd' } ]
While
req.checkHeader("referer").isNumeric();
console.log('errors', req.validationErrors());
results in a console output of:
ValidatorError: Invalid number
at new exports.ValidatorError (/node_modules/express-validator/node_modules/validator/lib/validator.js:6:11)
at Validator.error (/node_modules/express-validator/node_modules/validator/lib/validator.js:15:11)
at Validator.(anonymous function) [as isNumeric] (/node_modules/express-validator/node_modules/validator/lib/validator.js:57:33)
The log statement is never called and instead that stacktrace appears. Clearly something is wrong with the checkHeader function.
I was previously using version 0.7.0 of express-validator, and am looking to upgrade to the latest rev. One of the issues I'm encountering is a change in behavior on req.sanitize(). In the old version, it would return the sanitized value -- as well as set it on the req. In the new version, it does not return the sanitized value.
Since validator.js returns the sanitized value, I think it would be consistent to do the same from req.sanitize().
Testing express-validator per your example code. My code is as follows
app.post('/configure-stream', function(req, res){
req.assert('name', 'Invalid postparam').notEmpty()
var errors = req.validationErrors();
if (errors) {
res.send('There have been validation errors: ' + util.inspect(errors), 500);
return;
}
res.json({
name: req.body('name'),
});
});
$ express --version
= 3.0.0beta7
The response I'm getting is
TypeError: Object #<IncomingMessage> has no method 'assert'
Am I possibly overlooking a common configuration misstep? I required expressValidator and my app.configure block looks as follows:
app.configure(function(){
[...]
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
[...]
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(__dirname + '/public'));
app.use(app.router);
app.use(expressValidator);
});
req.sanitize('username').whitelist("ABC");
req.sanitize('username').blacklist("123");
throw Object [object Object] has no method
errors. Is there planned support for all sanitization methods available in validator?
request.check('email', 'Email is not valid').notEmpty().notNull().isEmail();
With no "email" field set this will return 3 repeatitions of the same message.
Shouldn't the error message be unified on chained call like this?
Thank you
req.checkHeader('Authorization', 'Authorization header cannot be empty).notEmpty();
This will fail with exception:
TypeError: Cannot read property 'Authorization' of undefined
at ~/node_modules/express-validator/lib/express_validator.js:173:33
at ~/node_modules/express-validator/lib/express_validator.js:81:21
at Array.map (native)
at IncomingMessage.checkHeader (~/node_modules/express-validator/lib/express_validator.js:79:13)
at app.get.res.statusCode (~/users.js:33:6)
at callbacks (~/node_modules/express/lib/router/index.js:164:37)
at param (~/node_modules/express/lib/router/index.js:138:11)
at param (~/node_modules/express/lib/router/index.js:135:11)
at pass (~/node_modules/express/lib/router/index.js:145:5)
at Router._dispatch (~/node_modules/express/lib/router/index.js:173:5)
I'd like to manually add validation errors for cases were complex validation is needed.
E.g.
req.validationError('name', 'Your name doesn\'t validate against our complex, possibly asynchronous validation logic.')
I don't want to mess with req._validationErrors
directly.
Does this sound reasonable?
Any chance this will get pulled if I create a PR?
the req.assert inside if(data === null) { never works! i get output in console.log, but it never causes validation error. Whereas the second one works perfectly.
async.eachSeries(associatedProfessionals_arr, function(item, cb) {
console.log(item);
var pair = item.split('[id:');
if(pair[1]) { // Check if it matches with a profile _id
var given_id = pair[1].split(']')[0];
if(given_id.match(/^[0-9a-fA-F]{24}$/)) {
Profile.findById(given_id, function(err, data){
if(err) throw err;
console.log(data);
if(data === null) {
console.log('couldn\'t find');
// isEmail() & phone has nothing to do. It just generates the error.
// req.assert('phone', 'The given associated id doesnt match.').isEmail();
req.assert('associatedProfessionals', 'The given associated id doesnt match.').genError();
cb();
} else cb();
});
} else {
req.assert('associatedProfessionals', 'Please insert the associated professionals field correctly.').genError();
cb();
}
} else cb();
}, function(err) {
if(err) throw err;
});
Here goes the genError custom validator:
expressValidator.Validator.prototype.genError = function() {
//You could validate against this.str, instead of just erroring out.
this.error(this.msg);
return this;
};
How to do xss filter of the params summit through POST method.
req.sanitize(name).xss(true) just for GET request?
Can anyone help me?
thanks!
Hello,
Node validator has escape mothod
escape() //Escape &, <, >, and "
But when I try to call this method under express-validator:
req.sanitize("param_name").escape()
I get an exception:
Object (here comes param value) has no method 'escape'
I'm doing this by the tutorial, am I doing everything correctly? Am I missing something?
// Modules
var express = require('express');
var util = require('util');
var expressValidator = require('express-validator');
var http = require('http');
var path = require('path');
var mongoose = require('mongoose');
var hasher = require('pwd');
var app = express();
// Configuration
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, '/public')));
app.use(express.bodyParser());
app.use(expressValidator());
mongoose.connect('mongodb://localhost:/test');
hasher.iterations(40000);
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.post('/admin/login', function(req, res) {
req.checkBody('username', 'Username must be minimum 3 characters long.').len(3); // error
req.checkBody('password', 'Password must be minimum 3 characters long.').len(3); // error
var errors = req.validationErrors();
res.json(errors);
});
http.createServer(app).listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
Hey, first of all: Great plugin! Gives you great control flow for your rest apis.
One thing: I wann a use matches, like it is available in https://github.com/chriso/validator.js but it's not working. If I use
req.assert('id', 'id should be valid').matches(/asd/);
matches is not found.
Is it intended or really missing?
Thanks
Hello,
I was just wondering if we can use chaining like the following in 'express-validator':
req.assert('emailAddress', 'Invalid email address').notEmpty().isEmail();
versus
req.assert('emailAddress', 'Invalid email address').notEmpty();
req.assert('emailAddress', 'Invalid email address').isEmail();
When I try chaining it in the first example, the second call says "Cannot call method 'isEmail' of undefined".
Can you please advise?
Currently sanitize only works on simple fields name.
I would like to reuse the check to sanitize some fields
req.sanitize('user.fields.email').trim();
req.sanitize(['user', 'fields', 'email']).trim();
In version 1.4.0 of express-validator you included Upgraded validator dependency to 1.1.3.
How can we use or include newer version validation dependency?
How can we extend that newer dependency?
I am getting an error when checking to see if the following
param = "STRINGA,STRINGB"
is in an array
array = ["StringA", "StringB", "StringA,StringB"]
my code does this:
req.assert('param', 'Invalid param').isIn(array);
This works when the param does not contain any comas, however the one above fails and throws the error below
Any ideas?
ReferenceError: err is not defined
at exports.employee (/Users/jyanes/Dev/leaveAdmin_EmployeeServices/routes/employee.js:185:27)
at callbacks (/Users/jyanes/Dev/leaveAdmin_EmployeeServices/node_modules/express/lib/router/index.js:164:37)
at param (/Users/jyanes/Dev/leaveAdmin_EmployeeServices/node_modules/express/lib/router/index.js:138:11)
at pass (/Users/jyanes/Dev/leaveAdmin_EmployeeServices/node_modules/express/lib/router/index.js:145:5)
at Router._dispatch (/Users/jyanes/Dev/leaveAdmin_EmployeeServices/node_modules/express/lib/router/index.js:173:5)
at Object.router (/Users/jyanes/Dev/leaveAdmin_EmployeeServices/node_modules/express/lib/router/index.js:33:10)
at next (/Users/jyanes/Dev/leaveAdmin_EmployeeServices/node_modules/express/node_modules/connect/lib/proto.js:193:15)
at Object.handle (/Users/jyanes/Dev/leaveAdmin_EmployeeServices/node_modules/express-validator/lib/express_validator.js:165:12)
at next (/Users/jyanes/Dev/leaveAdmin_EmployeeServices/node_modules/express/node_modules/connect/lib/proto.js:193:15)
at Object.multipart as handle
The mixinParams function is not necessary because Express 2.0 already provides support for accessing route params, query strings, and HTTP bodies with req.param(...)
See http://expressjs.com/guide.html#req.param() for more information
This should clean up the code a bit. :)
expressValidator = require('../../index'),
shouldn't this be something like require('express-validator')??
For example If you have form:
<form ...>
<input type="text" name="email"/>
<input type="text" name="email"/>
...
<input type="submit"/>
</form>
And then try to make on server
req.assert("email", "Invalid email" ).notNull().isEmail();
throws error =)
Something like this:
TypeError: Object [email protected],test, has no method 'match'
So ten year old "hacker" with curl
can easy drop my web site using such things=)
Looks like assert() supports nested params via an input array, but sanitze() does not. It would be nice if it did too.
Hi, I type "app.use(expressValidator());" in my app.js, then I type "node app.js" it give me some error:
req.assert("name", 'xxxx0-9,a-z,A-Z').isAlphanumeric();
^
TypeError: Cannot call method 'assert' of undefined
When I submit a single object as my payload I can validate keys very easily with:
req.checkBody('year', 'invalid year').len(4,4).isNumeric();
But I would like to submit an array of objects and loop through them with something like:
_.each(self.req.body, function(element, index, list) {
req.checkBody([index].year, 'invalid year').len(4,4).isNumeric();
});
I've also tried using req.assert
with element.year
and even element.year.toString()
with no luck.
What am I doing wrong? Or is this type of functionality even possible?
I have noticed that as I used the middleware I keep having to do the following:
var offset = parseInt(req.urlparams.offset);
if (offset) req.assert("offset", "Invalid Offset. Minimum of 0 mins.").isNumeric().min(0);
offset = offset || 0;
Basically I only want to validate the offset URL or Param value when it exists, otherwise I want to set the value to 0. This would dry out the code and let the middleware keep doing it job without the need for the if then statement.
Here is my proposed change to the same code:
var offset = parseInt(req.urlparams.offset);
if (offset) req.assert("offset", "Invalid Offset. Minimum of 0 mins.", 0).isNumeric().min(0);
offset = offset || 0;
It seems I can do this:
req.assert(['user', 'fields', 'email'] …or…req.assert(['user.fields.email'] when I VALIDATE (Check)… but this doesn’t seems to work with the sanitation methods?
How do I sanitize nested data?
If is possible to validate req.params.whatever fields?
These are special tokens, like:
app.get('/:username', routes.username);
The username would be req.params.username => 'chovy'
Thanks for such a helpful library, Christoph. Just wanted to report that it looks like version 0.7.0 of express-validator comes bundled with version 1.2.1 of validator, which actually has buggy implementations of isUUIDv4
and isUUIDv4
. (Both are lacking return
statements, so validation always fails.) A workaround is to call isUUID(3)
and isUUID(4)
, but the bugs do appear to have been fixed in version 1.3.0 (and higher) of validator. Cf. validatorjs/validator.js#204. (The bugs in question are in express-validator/node_modules/validator/lib/validators.js
.)
To customize things like defaultError, we need the node-validator instance.
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.